C#: Handling exception in WEB API 2 in 4 steps
Still with existing Web API (< version 2), We are unable to process some exceptions globally.
Problem statement
- Are you struggling to handle different type of exceptions?
- Exception handling code scattered across all the pages and source code?
- Using multiple Web API features to handle different type of exceptions?
Solution
In Web API 2, we got an easy way of implementation called "Global error handling".
Implementation Steps:
- Add a class file in web API solution. Call it as "GlobalErrorHandling.cs".
- Inherit the ExceptionHandler class.
- Override Handle() and write the exception handling code inside this method.
- In WebApiconfig, replace IExceptionHandler with GlobalErrorHandling class.
Example code snippets:
GlobalExceptionHandler.cs
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
//Write all exception handling logic here. Eg., Log into database/server, send mail.
}
}
WebApiConfig:
public static void Register(HttpConfiguration config)
{
//Exception handling
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
}