ASP.NET Core 2.0 Error Pages

Problem

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,

  1. public void Configure(  
  2.      IApplicationBuilder app,  
  3.      IHostingEnvironment env)  
  4.  {  
  5.      if (env.IsDevelopment())  
  6.      {  
  7.          app.UseDeveloperExceptionPage();  
  8.      }  
  9.      else  
  10.      {  
  11.          app.UseExceptionHandler(appBuilder =>  
  12.          {  
  13.              appBuilder.Run(async context =>  
  14.              {  
  15.                  var feature =  
  16.                      context.Features.Get();  
  17.                  var exception = feature.Error;  
  18.                  await context.Response.WriteAsync(  
  19.                      $"<b>Oops!</b> {exception.Message}");  
  20.              });  
  21.          });  
  22.      }  
  23.   
  24.      app.Run(async (context) =>  
  25.      {  
  26.          throw new ArgumentException("T must be set");  
  27.          await context.Response.WriteAsync("Hello Error Handling!");  
  28.      });  
  29.  }  

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

  1. app.UseExceptionHandler("/Error");  

Discussion

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

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 a path to MVC Controller/action and create error page using MVC Views. Note that the path must start with ‘/’

    • It is better to use only static content in error pages, to avoid them throwing an exception.
Source Code

GitHub