How to handle errors in ASP.NET Core?

ASP.NET Core provides a better way to handle the errors in Startup class as below.

    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    else
    {
    app.UseExceptionHandler("/Error");
    app.UseHsts();
    }
For development environment, Developer exception page display detailed information about the exception. You should place this middleware before other middlewares for which you want to catch exceptions. For other environments UseExceptionHandler middleware loads the proper Error page.
You can configure error code specific pages in Startup class Configure method as below.

    app.Use(async (context, next) =>
    {
    await next();
    if (context.Response.StatusCode == 404)
    {
    context.Request.Path = "/not-found";
    await next();
    }
    if (context.Response.StatusCode == 403 || context.Response.StatusCode == 503 || context.Response.StatusCode == 500)
    {
    context.Request.Path = "/Home/Error";
    await next();
    }
    });

Comments

Popular posts from this blog

ASP.NET Core | Change Token

ASP.NET Core | Open Web Interface for .NET (OWIN)

How will you improve performance of ASP.NET Core Application?