Part 20 Centralized exception handling in WCF by implementing IErrorHandler interface

Published on January 8, 2018

Link for all dot net and sql server video tutorial playlists

This is continuation to Part 19, please watch Part 19 before proceeding.

In this video, we will discuss – How to handle all WCF service exceptions in one central location. This is a very common interview
question.

In an ASP .NET web applications we can use Application_Error() event handler method in Global.asax to log all the exceptions and
redirect the user to a custom error page.

In WCF, to centralize exception handling and to return a general faultreason to the client, we implement IErrorHandler interface.

Let’s now look at the 3 steps involved in centralizing exception handling in WCF. We will be continuing with the same example, that
we worked with in Part 19.

Step 1: Implement IErrorHandler interface.

IErrorHandler interface has 2 methods for which we need to provide implementation.
1. ProvideFault() – This method gets called automatically when there is an unhandled exception or a fault. In this method we have
the opportunity to write code to convert the unhandled exception into a generic fault that can be returned to the client. ProvideFault() gets called before HandleError() method.

2. HandleError() – This method gets called asynchronously after ProvideFault() method is called and the error message is returned to
the client. This means that this method allows us to write code to log the exception without blocking the client call.

Step 2: Create a custom Service Behaviour Attribute to let WCF know that we want to use the GlobalErrorHandler class whenever an
unhandled exception occurs. GlobalErrorHandlerBehaviourAttribute class
1. Inherits from Attribute abstract class.
2. Implements IServiceBehavior interface. This interface has 3 methods (Validate(), AddBindingParameters(),
ApplyDispatchBehavior()). The implementation for Validate() and AddBindingParameters() method can be left blank. In the
ApplyDispatchBehavior() method, we create an instance of the GlobalErrorHandler class and associate the instance with each
channelDispatcher.
3. Has a constructor that contains one Type parameter. We will use this constructor in Step 3.

Step 3: Decorate CalculatorService class in CalculatorService.cs file with GlobalErrorHandlerBehaviourAttribute. Notice that this
attribute has one constructor that expects a single Type parameter. Pass GlobalErrorHandler class created in Step 1 as the
argument.
[GlobalErrorHandlerBehaviour(typeof(GlobalErrorHandler))]
public class CalculatorService : ICalculatorService
{
public int Divide(int Numerator, int Denominator)
{
}
}

https://cafeadobro.ro/

https://www.stagebox.uk/wp-includes/depo10-bonus10/

https://iavec.com.br/

Enjoyed this video?
"No Thanks. Please Close This Box!"