Techiehook Techiehook
Updated date Sep 06, 2024
This article explains how to implement global error handling and custom error pages in ASP.NET Core. It covers configuring middleware for handling unhandled exceptions, setting up custom error pages for different status codes (e.g., 404, 500), and optionally logging errors for debugging.

In ASP.NET Core, error handling and custom error pages can be managed globally by using middleware and custom error pages. In this article, we will see how to do that.

1. Global Error Handling with Middleware

ASP.NET Core provides a built-in feature for handling exceptions globally through middleware. We can configure this in the Startup.cs file by using the UseExceptionHandler method.

We will follow the below steps:

  • Add an error-handling middleware to catch unhandled exceptions.
  • Configure custom error pages based on the status codes.

Sample Code Snippt:

In Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        // Shows detailed error pages in development
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // Global error handler for production
        app.UseExceptionHandler("/Home/Error");
        // Handle 404 and other non-exception errors
        app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
    }

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

In this above configuration:

  • UseExceptionHandler("/Home/Error"): is used to redirect to a custom error-handling route if an unhandled exception occurs.
  • UseStatusCodePagesWithReExecute("/Home/Error/{0}"): is used to re-executes the request with the status code as a parameter for custom error pages, like 404 for "Not Found."

2. Custom Error Pages

We can also set up custom error pages to handle different status codes like 404 (Not Found), 500 (Internal Server Error), etc.

Sample Controller for Error Pages:

public class HomeController : Controller
{
    // Handles general errors
    [Route("Home/Error")]
    public IActionResult Error()
    {
        var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
        if (exceptionFeature != null)
        {
            // Log exception (could be saved to a database or logging service)
            var exception = exceptionFeature.Error;
            // You can pass this to your view if needed
        }
        return View();
    }

    // Handles specific status codes
    [Route("Home/Error/{statusCode}")]
    public IActionResult HandleErrorCode(int statusCode)
    {
        switch (statusCode)
        {
            case 404:
                return View("NotFound");  // View for 404 errors
            case 500:
                return View("ServerError");  // View for 500 errors
            default:
                return View("Error");  // Generic error view
        }
    }
}

Custom Error Views:

We can create specific views like NotFound.cshtml, ServerError.cshtml, and Error.cshtml inside the Views/Home folder to handle each type of error.

simple NotFound.cshtml view:

@{
    ViewBag.Title = "Page Not Found";
}

<h1>404 - Page Not Found</h1>
<p>The page you are looking for does not exist.</p>
<a href="/">Return to Home</a>

3. Enabling Detailed Error Pages in Development

In the development, it is helpful to use detailed error pages with the UseDeveloperExceptionPage middleware:

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

This gives developers full stack traces and other information that can be useful during debugging.

4. Logging Errors (Optional)

ASP.NET Core has a built-in logging support. We can log exceptions during global error handling:

public void Configure(IApplicationBuilder app, ILogger<Startup> logger)
{
    app.UseExceptionHandler(errorApp =>
    {
        errorApp.Run(async context =>
        {
            var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
            logger.LogError(exceptionHandlerPathFeature?.Error, "An unhandled exception occurred.");
            context.Response.Redirect("/Home/Error");
        });
    });
}

The above code will log any unhandled exceptions and redirect the user to the error page.

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!