I have in my startup.cs file:
if (env.IsDevelopment()) {
app.UseExceptionHandler("/api/error/error-local-development");
}
else {
app.UseExceptionHandler("/api/error/error");
}
But when throw new Exception() in a controller action, the Error controller Methods are never called.
[Route("api/error")]
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorController : OwnBaseController
{
public ErrorController(IApplicationUserService applicationUserService, ILogger<ErrorController> logger, IDiagnosticContext diagnosticContext) : base(applicationUserService, logger, diagnosticContext)
{
}
[Route("error")]
public IActionResult Error()
{
return Problem();
}
[Route("error-local-development")]
public IActionResult ErrorLocalDevelopment([FromServices] IWebHostEnvironment webHostEnvironment)
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message);
}
}
Why is this not working?
It might seem strange but ordering does matter.
UseExceptionHandler and UseRouting are both registering middlewares under the hood.
The firstly registered will be the outer most middleware. So, if one of the inners throws an exception the outer can catch and handle it.
Source
MSDN has some warnings about this, for example:
If an endpoint within the app is specified, create an MVC view or Razor page for the endpoint. Ensure
UseStatusCodePagesWithReExecuteis placed beforeUseRoutingso the request can be rerouted to the status page.
UseExceptionHandleris the first middleware component added to the pipeline. Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.
It didn't help for me so, I changed this
app.UseExceptionHandler("Home/Error");
to this
app.UseExceptionHandler("/Error");
and aldo added an attribute route on the action
[Route("/Error")]
public IActionResult Error()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With