exceptionfiltererror-handlingasp.net-core-middlewareexceptionhandler

Handle Errors on Asp.net core6 mvc


I am studying asp.net core and I need to fix error handling problems.

I have some questions about them

1- should we catch all error types and return specific views each of them? 400 401 403 404 500 and more

2-if yes, which method is the best practice? Middleware or filters or any other? Can you share some samples please?

3-if no, what kind of route should I follow for errors ?


Solution

  • You can get all the response codes, it's up to you whether you need to display a different page for each code.

    For example, use UseStatusCodePagesWithReExecute middleware:

    Program.cs:

    app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
    

    Controller:

    public IActionResult Error(int? statusCode = null)
    {
        if (statusCode.HasValue) 
        {
            ViewData["Message"] = statusCode;
            return View("ErrorPage");
        }
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
    
    [Route("ErrorPage")]
    public IActionResult ErrorPage()
    {
        return View();
    }
    

    In ErrorPage.cshtml, you can use ViewData["Message"] to get the response code and display different content for it.

    Or you can create a view for each response code like this.

    For more details, you can refer to this document.