Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save boubkhaled/4c34cc3ea5e8e06c60572eff36481889 to your computer and use it in GitHub Desktop.
Save boubkhaled/4c34cc3ea5e8e06c60572eff36481889 to your computer and use it in GitHub Desktop.
#15 Stefan's Newsletter: Global Error Handling in .NET

Global Error Handling in .NET

Today we will show in a quick and simple way how we can handle errors at the global level of the application within just one file.

Global error handling in .NET allows developers to centralize error or exception handling in a single location rather than scattering error handling code across the application.

In .NET 5+, the recommended approach to implement global error handling is using middleware.

This is absolutely the simplest and most effective way, the implementation of which takes only 5 minutes. Now I will show you how to do it.

Exception Middleware

First, you need to create a middleware. You can call it
ExceptionMiddleware.

The middleware should look like this:

image

This middleware will catch any exception thrown from the application and write a general error message back to the response.

Extra explanation:

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.

The code in catch code block can be extracted in a separated method.

Add middleware to Pipeline

Next, you need to add this middleware to the middleware pipeline. This is done in the Program.cs file (the Startup.cs file, specifically in the Configure method before .NET 6).

Adding middleware to Pipeline:

image

You should add the ExceptionMiddleware before other middleware. This ensures that it can catch exceptions thrown from any subsequent middleware or from your controllers.

What next?

This approach is customizable.

For example, you might choose to log the exceptions, or return different responses depending on the type of exception thrown. But in its most basic form, this is how you can implement global error handling in .NET using middleware.

That's all from me today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment