This video is available to students only

Creating Exception Middleware

In this lesson, we're going to create exception middleware to handle internal server error

Creating exception middleware#

We have made our not found error, bad request error and unknown endpoint error consistent. Let's work on making our Internal server error the same, which looks like this right now. In production, this error doesn't mean anything, but in development, we still want to show this stack trace, as it contains some useful information for the developer.

We can start working on it now. We do have an ApiResponse class which is responsible for sending the status code and the error message, but for this particular error, we need to add the error details as well, so we can extend it to include the details field to our error response. We can create a new class inside the ErrorResponse folder and call it ApiException. This will derive from the ApiResponse. Now we can create a constructor which already has statusCode and an error message. To include error details, we can create a new property here called Details and add it to the constructor, with default value as null, and inside, we can set the Details property to be details, which we receive from the constructor.


Now that we have created an exception class, we need to create a middleware which will be responsible for showing this particular exception. Inside the API project, we will create a new folder called Middleware, and a new class called ExceptionMiddleware. We will create a constructor and inject RequestDelegate which will be called next. Let's import it from Microsoft.AspNetCore.Http. We need ILogger which will be called logger. It takes a type so we can call it ExceptionMiddleware. We can import it as well from Microsoft.Extensions.Logging. We also want our environment details, so we can use IHostEnvironment which will be called env, let's import it from Microsoft.Extensions.Hosting. Now let's initialize the fields from parameter for three of them.

Start a new discussion. All notification go to the author.