Explain how error handling works in ASP.NET Core

When building or using web applications, it’s very common to run into errors. Hence it’s important to configure error handling for your web application and handle the errors gracefully to provide a suitable response to the user. This improves the usability of your application as well as makes it robust.

There are many different errors that can happen in a normal application flow. However, the two important types of errors are exceptions and error status codes, e.g. 404, 502. Exceptions occur when the app runs into an unexpected circumstance. A very common example of an exception is the notorious NullReferenceException, which is thrown whenever you try to call a method or access a property on a null object.

When an exception occurs in the middleware pipeline, it propagates back through the pipeline, giving each middleware an opportunity to handle the exception. If no middleware catches the exception, the framework returns a 500 error status code to the user. The 500 status code stands for the ‘server error’, indicating something went wrong on the server.

Sometimes, an error doesn’t cause an exception, instead returning an error status code directly. For example, when the router can’t handle a URL path it returns a generic 404 error status code.

Error handling middleware allows you to modify the response before it’s sent to the user. By controlling the error response, you can show user-friendly errors that provide more information on what went wrong, as well as avoid exposing any sensitive information to the user. In general, the error handling middleware returns the error details, or it can generate a friendly HTML page to be sent in the response.

The best practice is to place the error handling middleware as early in the middleware pipeline. This ensures that it will catch any errors generated by the application as well as the subsequent middleware. It’s configured like all middleware, in the Startup.Configure() method.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
   if (env.IsDevelopment()){

   app.UseEndpoints(endpoints =>{
         name: "default",
         pattern: "{controller=Home}/{action=Index}/{id?}");

You can see that the above code configures a developer exception page for the development environment and also configures a custom error handling page for the production environment. The developer exception page provides additional details to help you troubleshoot errors in development. It contains the exception information such as the stack trace, query params, cookies, headers, etc.

Updated on: 22-Jun-2021


Kickstart Your Career

Get certified by completing the course

Get Started