Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ASP.NET Core's app.UseExceptionHandler() not working?

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?

like image 859
edelwater Avatar asked Jan 26 '26 07:01

edelwater


2 Answers

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.

middleware ordering Source

MSDN has some warnings about this, for example:

  • Handle Errors in ASP.NET Core's UseStatusCodePagesWithReExecute section

If an endpoint within the app is specified, create an MVC view or Razor page for the endpoint. Ensure UseStatusCodePagesWithReExecute is placed before UseRouting so the request can be rerouted to the status page.

  • ASP.NET Core Middleware's Middleware order section

UseExceptionHandler is the first middleware component added to the pipeline. Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.

like image 64
Peter Csala Avatar answered Jan 27 '26 21:01

Peter Csala


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()
like image 27
miri l. Avatar answered Jan 27 '26 21:01

miri l.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!