다음을 통해 공유


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

  1. Are you struggling to handle different type of exceptions?
  2. Exception handling code scattered across all the pages and source code?
  3. 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:

  1. Add a class file in web API solution. Call it as "GlobalErrorHandling.cs".
  2.  Inherit the ExceptionHandler class.
  3.  Override Handle() and write the exception handling code inside this method.
  4. 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());
 }