To explicitly control the behavior of the application when an exception is thrown, implement the IErrorHandler interface and add it to the ErrorHandlers property. IErrorHandler enables you to explicitly control the SOAP fault generated, decide whether to send it back to the client, and perform associated tasks, such as logging. Error handlers are called in the order in which they were added to the ErrorHandlers property.
Implement the ProvideFault method to control the fault message that is returned to the client.
Implement the HandleError method to ensure error-related behaviors, including error logging, assuring a fail fast, shutting down the application, and so on.
Note: |
|---|
Because the HandleError method can be called from many different places there are no guarantees made about which thread the method is called on. Do not depend on HandleError method being called on the operation thread. |
All ProvideFault implementations are called first, prior to sending a response message. When all ProvideFault implementations have been called and return, and if fault is non-nullNothingnullptra null reference (Nothing in Visual Basic), it is sent back to the client according to the operation contract. If fault is nullNothingnullptra null reference (Nothing in Visual Basic) after all implementations have been called, the response message is controlled by the ServiceBehaviorAttribute..::.IncludeExceptionDetailInFaults property value.
Note: |
|---|
Exceptions can occur after all ProvideFault implementations are called and a response message is handed to the channel. If a channel exception occurs (for example, difficulty serializing the message) IErrorHandler objects are not notified. In this case, you should make sure that your development environment catches and displays such exceptions to you or makes use of tracing to discover the problem. For more information about tracing, see Using Tracing to Troubleshoot Your Application. |
After the response message has been sent, all HandleError implementations are called in the same order.
Typically, an IErrorHandler implementation is added to the ErrorHandlers property on the service (and the client in the case of duplex communication).
You can add the IErrorHandler to the runtime by implementing a behavior (either an System.ServiceModel.Description..::.IServiceBehavior, System.ServiceModel.Description..::.IEndpointBehavior, System.ServiceModel.Description..::.IContractBehavior, or System.ServiceModel.Description..::.IOperationBehavior object) and use the behavior programmatically, from a configuration file or with a custom attribute to attach your IErrorHandler.
For more information about using behaviors to modify the runtime, see Attaching Extensions Using Behaviors.