In today’s newsletter we are going to discuss
Introduction of global exception
Pros and cons of global exception
How to implement it via middleware’s
Introduction of Global Exception
We often come up with exceptions in our application and we have two ways in general to handle those exception.
Handle at controller/service level everywhere in application
Handle from one place and control the application
Those approaches are fine and work well , I would like to talk about second one today
Pros and Cons of Global Exception
Let’s see pros and cons of this approach
Pro (s) :
Code becomes easy to manage because we don’t need to look into n different
try-catch
blocks , just look from one place and deal them.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. Additionally it is a good approach to log those exceptions (Check my post on How to add logs via NLog or my friend Milan post on Logging with Serilog in .NET Core)
Con (s) :
A global exception handler can make it harder because sometime it will catch the exception at broad level and deal with it accordingly without digging down to exact lower-level exception
If you are on short time and you need to implement exception handling then global exception handling is the best solution.
How to Implement it via Middleware
We have different ways to implement global exception handling in our .NET application e.g. using custom/built in exception filter or creating our custom middleware using IMiddleware
and implementing its methods.
So every time before and after controller request will come in this middleware and we would add try-catch block here and request would be caught here.
Step 1 : Create Middleware
If you are worried about what is JsonConvert.SerializeObject(response)
then check post on ‘Serialization’.
Step 2 : Register the Middleware as a Service and then use it in Middleware in Program.cs
That’s all you need to do. Now you can add any exception by throw new Exception("This is a test exception");
and test it if it works or not
Whenever you’re ready , there are 3 ways I can help you
Promote yourself to 2500+ subscribers by sponsoring my Newsletter (Reach me at mwaseemzakir@gmail.com)
Become a Patron and get access to 100+ .NET Questions and Answers
Get my FREE eBook from Gumroad that contains 30 .NET Tips (1100+ Downloads)
Special Offers 📢
Ultimate ASP.NET Core Web API Second Edition - Premium Package
10% off with discount code: 9s6nuez