简体   繁体   English

处理和引发FaultException的最佳实践

[英]Best practice to handle and throw FaultException

I am in situation where I need to find the best possible approach to do this, 我处于需要寻找最佳方法来执行此操作的情况下,

try
{
  // Service call.
}
 catch (FaultException exception)
      {
        service.Abort();
        throw new FaultException(Resources.UnexpectedErrorOccurredAtServer, exception);
      }

Or 要么

catch (FaultException exception)
      {
        service.Abort();
        throw new Exception(Resources.UnexpectedErrorOccurredAtServer, exception);
      }

// Caller. //来电者。

Main()
{
try
{
 serviceCaller()
}
catch(FaultException ex)
{
  // Should we have this catch???
}
catch( Exception ex)
{
  // Handle unexpected errors.
}

what will be the best approach to throw the expected exception to caller. 将预期异常抛出给调用方的最佳方法是什么? If we throw FaultException caller main method should Handle it explicitly or general exception will work. 如果抛出FaultException,则调用方的main方法应显式处理它,否则常规异常将起作用。

The best approach would be 最好的方法是

try
{
  // ...
}
catch (FaultException ex)
{
    service.Abort();
    throw;
}

This preserves the stack trace, which your proposed methods do not. 这将保留堆栈跟踪,而您提议的方法则不会。 See Throwing Exceptions best practices . 请参阅“ 抛出异常”最佳实践

You may be interested to check WCF error handling and some best practices 您可能有兴趣检查WCF错误处理和一些最佳做法

The best approach would be like this:- 最好的方法是这样的:

try
{
  proxy.SomeOperation();
}
catch (FaultException<MyFaultInfo> ex)
{
  // only if a fault contract was specified
}
catch (FaultException ex)
{
  // any other faults
}
catch (CommunicationException ex)
{
  // any communication errors?
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM