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. Consider the following example of Configure method which throws an error.
The above code will display the following result.
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. If not then you can add Microsoft.AspNetCore.Diagnostics package via NuGet manager.
The Microsoft.AspNetCore.Diagnostics package includes following extension methods to handle exceptions in different scenario:
- UseDeveloperExceptionPage
- UseExceptionHandler
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.
As this middleware displays sensitive information, it is advisable to add it only in development environment.
UseExceptionHandler
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.
In the above example, the UseExceptionHandler("/Home/Error") sets the error handler path. If an error occurred in the MVC application then it will redirect the request to /home/error, which will execute the Error action method of HomeController In case of Production environment.
Exception filters
In MVC apps, exception filters can be configured globally or on a per-controller or per-action basis. In Razor Pages apps, they can be configured globally or per page model. These filters handle any unhandled exception that occurs during the execution of a controller action or another filter. For more information, see Filters in ASP.NET Core.
Refrence: https://www.tutorialsteacher.com/, https://docs.microsoft.com
0 comments:
Post a Comment