ASP.NET Core 2.0 Error Pages

Problem

How to serve error pages in ASP.NET Core application.

Solution

Starting from an empty project, created in a previous post, amend the Configure() method of Startup class to use middleware needed for error handling. Below I’ve used a custom middleware (defined as lambda) to handle production exceptions:

Alternatively you could point to MVC controller/action, which would return a ViewResult:

Discussion

It is really simple to configure middleware to setup error pages for both development and production environment.

The error page for development environment shows all the relevant details that developers require to resolve the issue. However, this page is not suitable for production/end-user, it gives too much information which could be used for malicious reasons.

There are two ways we can show user and production friendly error pages:

  1. Plug-in a middleware into UseExceptionHandler (which itself is a middleware). This gives a lot of flexibility on how to build an error response.
  2. Provide path to MVC controller/action and create error page using MVC views. Note that the path must starts with ‘/’
    • It is better to use only static content in error pages, to avoid them throwing exception.

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Asp.ErrorHandlingpre>

Leave a Reply