Which .net exception to throw when the server throws an unexpected exception via webservice

纵饮孤独 提交于 2019-12-25 05:08:33

问题


Which .net exception should throw the client (or better re-throw), if it catches any unexpected exception from the server (e.g. wrapped in as FaultException via WCF, the server can be written on java) to handle it further on client as follow:

  • The client shows the user a message about the possible bug in client/server
  • The client provides developers the details of this exception (e.g. per e-mail)

Example in the business layer:

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);
}

Provides the .net framework any exceptions for (UnexpectedServerException in this example), if not, which exception would you create?


回答1:


The following example shows the usual exception handling for WCF clients:

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
}



回答2:


Why catch the exception at all?

You should not catch exceptions that you can't correct. You don't seem to be able to correct any of the exceptions you're catching, so why catch them at all?



来源:https://stackoverflow.com/questions/9379191/which-net-exception-to-throw-when-the-server-throws-an-unexpected-exception-via

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!