Alexander Zwitbaum
Alexander Zwitbaum

Reputation: 4846

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

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:

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?

Upvotes: 0

Views: 297

Answers (2)

Michael Damatov
Michael Damatov

Reputation: 15623

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
}

Upvotes: 1

John Saunders
John Saunders

Reputation: 161773

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?

Upvotes: 1

Related Questions