Search code examples
asp.net-core-mvccustom-error-pagesasp.net-core-2.2

How to handle Custom Errors With .Net Core 2.2 MVC


I saw on youtube how to handle custom errors but it was with web.config and in dotnet core 2.2 it does not have this file or I'm not finding it through visual studio 2019.


Solution

  • ASP.NET Core doesn't use Web.config, unless you're hosting in IIS, and then only for minimal IIS module configuration. Custom error handling is done via middleware configuration in your Startup.Configure method. This is actually covered in the default project template, though, so it's odd that you don't have something included by default to at least work from. Regardless, you're looking at something like:

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

    That will generally route any global uncaught exception to a general /Error endpoint, which could be either a controller action or Razor Page. More likely than not, you'll want a little more flexibility, and you will also want to not expose an actual "error" URL in the browser, so you'll probably sub UseExceptionHandler with UseStatusCodePagesWithReExecute:

    app.UseStatusCodePagesWithReExecute("/StatusCode","?code={0}");
    

    That will keep the URL, without redirecting and load up a /StatusCode endpoint while passing the specific status code (404, 400, 500, etc.), allowing you to return custom messaging per error type.

    All of this and more is in the documentation.