当服务器通过webservice引发意外异常时抛出哪个.net异常

时间:2012-02-21 14:23:50

标签: .net web-services exception client

如果它从服务器捕获任何意外的异常(例如,通过WCF包装为FaultException,服客户如下:

  • 客户端向用户显示有关客户端/服务器中可能存在错误的消息
  • 客户端向开发人员提供此异常的详细信息(例如,通过电子邮件发送)

业务层中的示例:

var client = new MyWcfClient());
try {
  // Try get data.
  var data = client.getSomeData(id);
  if(data == null) {
    // Unexpected exceptions from the server.
    // throw new Exception???
  }
} catch(FaultException<Specified1Exception> exception) {
  // Handle e.g. re-throw.
  // Shows the user the myErrorText.
  throw new InvalidOperationException(myErrorText)
} catch(FaultException<Specified2Exception> exception) {
  // Handle e.g. re-throw.
  // Enforce to show the user some dialog.
  throw new ArgumentException(param, myText);
} catch(FaultException exception) {
  // Unexpected exceptions from the server.
  // throw new UnexpectedServerException???
} catch(Exception exception) {
  // WCF error, like communication timeout, soap etc.
  throw new InvalidOperationException(myOtherErrorText);
}

为.net框架提供(本例中为UnexpectedServerException)的任何异常,如果没有,您会创建哪个异常?

2 个答案:

答案 0 :(得分:1)

为什么要捕捉异常?

您不应该捕获无法纠正的异常。您似乎无法纠正您捕获的任何异常,那么为什么要捕获它们呢?

答案 1 :(得分:1)

以下示例显示了WCF客户端的常见异常处理:

try
{
    ... // service call
}
catch (FaultException<X> e)
{
    // handle fault specified as [FaultContract(typeof(X))]
}
catch (FaultException<Y> e)
{
    // handle fault specified as [FaultContract(typeof(Y))]
}
catch (FaultException e)
{
    // handle all other faults NOT specified as [FaultContract]
    // these are unhandled exception thrown by the service
}
catch (CommunicationException e)
{
    // handle all communication-layer exceptions
    // these are exceptions thrown by the WCF infrastucture
}