Global Exception Handling with .NET Core 7 – C#

by
Ali Hasan
.net-7.0 asp.net-core-6.0 asp.net-core-middleware c#

The Problem:

In a .NET Core 7 application, the developer is experiencing difficulties implementing global exception handling. They have created custom middleware and an ExceptionHandler, but neither of these solutions is capturing unexpected exceptions. The raw error and stack trace are being returned in a plaintext response instead of the desired JSON response with a 500 status code. The ExceptionHandler is never called, and the middleware’s catch block is not being executed. The developer has confirmed that the middleware is being loaded, but the error is not being caught. They suspect a missing step or an issue with using a multi-tier architecture without async methods. They have attempted to throw an exception directly in an endpoint handler, but that also resulted in the raw stack trace being returned.

The Solutions:

Solution 1: Fixed `UseMiddleware` Order

The issue was with the order of middleware in the `Startup.cs` file. The `app.UseMiddleware()` line should be placed before `app.UseEndpoints(endpoints => { … })` for the middleware to execute properly and capture exceptions.

Solution 2: Using `UseDeveloperExceptionPage`

Ensure error handling middleware is added before UseDeveloperExceptionPage. The order of registration of middleware matters. When UseDeveloperExceptionPage is present before other error handling middleware, it will handle errors before the others. Remove UseDeveloperExceptionPage to allow other middleware to handle exceptions.

Q&A

What is one reason a middleware might not be called to handle exceptions?

Middleware must be added before app.UseEndpoints is called in Startup.cs.

What is the role of middleware?

Middleware is a software component that can be used to intercept and handle requests before they reach the application code.

What is one way to determine the order of middleware execution?

Middleware is executed in the order that it is added in the Startup.cs file.

Video Explanation:

The following video, titled "Elegant Global Error Handling Using Middleware In ASP.NET Core ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... c/MilanJovanovicTech?sub_confirmation=1 Chapters 0:00 What is ... 7:52 · Go to channel · BEYOND Status Codes! Better REST HTTP API Error ...