Exception Handling in Asp.NET Core 3.1
Exception handling is one of the most important features of any application. Fortunately, ASP.NET Core includes a middleware that makes exception handling easy.
By default, ASP.NET Core returns a simple status code for any exception that occurs in an application
Handle Exceptions
Install Microsoft.AspNetCore.Diagnostics Package
To handle exceptions and display user friendly messages, we need to install Microsoft.AspNetCore.Diagnostics NuGet package and add middleware in the Configure() method. If you are using Visual Studio templates to create ASP.NET Core application then this package might be already installed.
The Microsoft.AspNetCore.Diagnostics package includes following extension methods to handle exceptions in different scenario:
1. UseDeveloperExceptionPage
The UseDeveloperExceptionPage extension method adds middleware into the request pipeline which displays developer friendly exception detail page. This helps developers in tracing errors that occur during development phase.
This middleware displays sensitive information, it is advisable to add it only in development environment.
Stack: The Stack tab gives the information of stack trace, which indicates where exactly the exception occurred, the file name, and the line number that caused the exception.
Query: The Query tab gives information about the query strings.
Cookies: The Cookies tab displays the information about the cookies set by the request.
Header: The Header tab gives information about the headers which is sent by the client when he makes the request.
Routing: The Routing tab gives information about the Route Pattern and Route HTTP Verb type of the method, etc.
In MVC Core application, we might want some other controller to handle all exceptions and display custom user friendly error messages. The UseExceptionHandler extension method allows us to configure custom error handling route. This is useful when an application runs under production environment.
If you are working with any older versions of .NET Core Application, in order to display a page that shows detailed information about the unhandled exception, you need to configure the Developer Exception Page Middleware in the Request Processing Pipeline. To do so, you need to modify the Configure() Method of the Startup class as shown below to add the Developer Exception Page middleware, which will handle the unhandled exception that occurred in your application.
UseDeveloperExceptionPage => To customize UseDeveloperExceptionPage middleware, we need to use the DeveloperExceptionPageOptions object.
UseDefaultFiles => To customize UseDefaultFiles middleware, use the DefaultFilesOptions object
UseStaticFiles => To customize UseStaticFiles middleware, use the StaticFileOptions object
UseFileServer => To customize UseFileServer middleware, use the FileServerOptions object