Error Handling

Developer Exception Page

The Developer Exception Page displays detailed information about request exceptions. The page is made available by Microsoft.AspNetCore.Diagnostics package, which is in the Microsoft.AspNetCore.App metapackage.

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    // ...
}

Enable the Developer Exception Page only when the app is running in the Development environment.

Exception handler page

To configure a custom error handling page for the Production environment, use the Exception Handling Middleware. The middleware:

  • Catches and logs exceptions.

  • Re-executes the request in an alternate pipeline for the page or controller indicated.

if (env.IsDevelopment())
{
    // ...
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

Database error page

The Database Error Page middleware captures database-related exceptions that can be resolved by using Entity Framework migrations.

if (env.IsDevelopment())
{
    app.UseDatabaseErrorPage();
}

Exception filters

Exception filters:

  • Implement IExceptionFilter or IAsyncExceptionFilter.

  • Can be used to implement common error handling policies.

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public CustomExceptionFilterAttribute(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    public override void OnException(ExceptionContext context)
    {
        if (_hostingEnvironment.IsDevelopment())
        {
            var result = new ViewResult {ViewName = "CustomError"};
            context.Result = result;
        }
    }
}

Last updated