user2174775
user2174775

Reputation: 1

ASP.NET Core 8: error controller method catches the error code, but does not display requested view

I'm using NLog so that when server gets error will direct action to ErrorController.

Program.cs:

app.UseStatusCodePagesWithReExecute("/Error/{0}"); 
app.UseExceptionHandler("/Error");

ErrorController.cs:

[Route("/Error/{statusCode?}")]
public IActionResult Error(int? statusCode)
{
        if (statusCode.Value == 500) 
        {
            _logger.LogError($"A 500 error occurred.");
            ViewBag.ErrorMessage = "An error occurred while processing your request.";
            return View("Error");  // Generic error view                  
        }
        else if (statusCode.Value == 404)
        {
            _logger.LogError($"Error 404"); 
            return View("NotFound"); // Specific 404 view
        }

        _logger.LogError($"An unexpected {statusCode.Value} error ocurred.");
        return View("Error");  // Generic error view             
    }
    else   // statusCode is null (general error, or error within this controller)
    {        
        ViewBag.SectionTitle = "Error";
        return View("Error");  // Default error view
    }
}

Views/Error - Error.cshtml, NotFound.cshtml

To test I added Division by Zero line to another controller, with a catch block like:

catch (Exception ex)
{
    _logger.LogError($"{MethodBase.GetCurrentMethod()?.Name}: An unexpected error occurred: {ex.Message}"); // Log the exception
    return StatusCode(500);
}

A http 500 error is caught by ErrorController and it executes return View("Error"), but does NOT display the view, on the contrary continues the execution of the website (goes to next page) where there is another division by zero, throws a http 500 error caught by ErrorController, executes return View("Error") but again continues the execution of the website (goes to next page) that does not exist, a http 404 error is caught by ErrorController and it executes return View("NotFound"); therefore I see the custom NotFound.cshtml.

Why is it not stopping and displaying the Error.cshmtl page?

Both "division by zero" errors are in a HomeController method that is POST from Javascript 'fetch' function on each page (before moving to the next page I am saving the user selections in a session variable).

If the error happens BEFORE displaying the page, this setup correctly throws a 500 error that is caught by ErrorController and displays the Error.cshtml page.

Any ideas why?

Upvotes: 0

Views: 47

Answers (1)

Rena
Rena

Reputation: 36715

You need change the code below to enforce default exception handler also work in ErrorController:

app.UseExceptionHandler("/Error/500");

Upvotes: 0

Related Questions