Global Exception Handling in ASP.NET WEB API
WebAPI
19 Articles
In this article, let's learn about Global Exception Handling in Web API in ASP.NET Core.
Note: If you have not done so already, I recommend you read the article on Importance of Status Code in Web API.
Table of Contents
- Introduction
- Why Global Exception Handling ?
- Creating a Custom Error Handling Middleware
- Advantages
- Summary
Introduction
Exception is a common thing we often come up with it in our applications. This happens when something goes wrong exceptionally. All the known paths in code can be handled to return expected response. And for unhandled exceptions or server faults, Global Exception Handling comes to rescue.
Global Exception Handling - This is where we handle exceptions globally in one single place inside the application rather than scattering the try catch blocks everywhere in the code base. This is a good and clean practice and the absolutely simplest way.
This is the first thing that I do when I create new Web API Projects or when I work on existing code base. Let's focus and learn on the simplest and cleanest way of handling exceptions globally in ASP.NET Web API.
Why Global Exception Handling ?
Handling exceptions locally in the method where it is thrown is what I have seen in most of the code bases. This often grows and pollutes the code base. I have seen projects having try catch blocks everywhere in the code base starting from controller to services to repositories. This is not a good practice and it increases the complexity of the code base and makes it difficult to read and maintain. This is where Global Exception Handling comes to rescue.
Creating a Custom Error Handling Middleware
Note: If you have not done so already, I recommend you read the article on Introducing Middleware in ASP.NET.
Here are the steps to implement Custom Global Exception Middleware,
Create Global Exception Middleware as shown below
Code Sample - Global Exception Middleware in ASP.NET
This middleware inheriting from IMiddleware will catch any exception thrown from the application and write a general error message back to the response on Prodcution environment and the actual error message on Non Production environment.
RequestDelegate next is a function delegate representing the next middleware component in the request pipeline. InvokeAsync is the heart of the middleware. It is called for every request that passes through the middleware. It takes an HttpContext object as a parameter, which represents the HTTP request and response.
In the try block, we're calling next, which effectively passes control to the next middleware in the pipeline. If there's an exception anywhere after this line, control will return back to this middleware.
Register it as the first Middleware as shown below
Code Sample - Registering Global Exception Middleware in ASP.NET
From the above code, we can see that we are registering the UseGlobalExceptionMiddleware() as the first Middleware in the pipeline. This is important because we want to catch all the exceptions that are thrown from the application. If we register it at the end of the pipeline, then it will not catch all the exceptions.
Advantages
The advantages of Global Exception Handling are as follows,
- Single point to handle and log exceptions.
- Code becomes easy to manage because we don't need to look into n different try-catch blocks.
- More readable because a few lines of code managing the whole exceptions of application.
- Removes repeated code (try-catch everywhere).
- It gives us more control so we can catch exceptions and return response of our own type, in most cases we return Internal Server Error.
Summary
In this article, we learnt about the simplest and easiest way to handle exception globally in ASP.NET Web API using a custom middleware. We also learnt about the advantages of handling exceptions globally. I hope you enjoyed reading it.