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:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(appBuilder =>
{
appBuilder.Run(async context =>
{
var feature =
context.Features.Get();
var exception = feature.Error;
await context.Response.WriteAsync(
$"<b>Oops!</b> {exception.Message}");
});
});
}
app.Run(async (context) =>
{
throw new ArgumentException("T must be set");
await context.Response.WriteAsync("Hello Error Handling!");
});
}
Alternatively, you could point to MVC controller/action, which would return a ViewResult
:
app.UseExceptionHandler("/Error");
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 in which we can show user and production friendly error pages:
- Plug-in a middleware into
UseExceptionHandler
(which itself is a middleware). This gives a lot of flexibility on how to build an error response.
- 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.