Tuesday 23 May 2023

How to implement global exception handling in .NET Core

  Hello friends,

 In this article, I will explain What is global exception and Pros and cons of global exception and  

  • 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 that exception.

  • Handle at controller/service level everywhere in the application
  • Handle from one place and control the application

 

Pros and Cons of Global Exception

Let’s see the pros and cons of this approach

Pros  :

  • 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 with them.
  • More readable because a few lines of code managing the whole exceptions of the application
  • Removes repeated code (try-catch everywhere)
  • It gives us more control so we can catch exceptions and return responses of our own type, in most cases we return Internal Server Error.  

Cons :

  • A global exception handler can make it harder because sometimes it will catch the exception at a broad level and deal with it accordingly without digging down to the 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 a try-catch block here and the 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 throwing a new Exception("This is a test exception"), and test if it works or not


 Happy programming!!

Don’t forget to leave your feedback and comments below!

Regards

Sujeet Bhujbal

--------------------------------------------------------------------------------

Blog: www.sujeetbhujbal.com

Personal Website :-http://sujeetbhujbal.wordpress.com/ 

CodeProject:-http://www.codeproject.com/Members/Sujit-Bhujbal 

CsharpCorner:-http://www.c-sharpcorner.com/Authors/sujit9923/sujit-bhujbal.aspx

Linkedin :-http://in.linkedin.com/in/sujitbhujbal 

Twitter :-http://twitter.com/SujeetBhujbal 

------------------------------------------------------------------------------