Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "UseDeveloperExceptionPage" together with "UseExceptionHandler"

I want to show the developer exception page when there is an unhandled exception but I also want to add logging to it. But when I use app.UseDeveloperExceptionPage together with app.UseExceptionHandler, only the last one I add works. How can I make the two work together?

like image 851
hakanviv Avatar asked Feb 22 '19 11:02

hakanviv


2 Answers

The default ExceptionHandler does not work with the DeveloperExceptionPage because it catches the Exception.
What you can do is add an ExceptionFilter, log the Exception and let it be caught by the DeveloperExceptionPage:

public class ExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        Log.Error(context.Exception, $"{context.ActionDescriptor.DisplayName}");

        // the important bit here
        context.ExceptionHandled = false;
    }
}

And then add it to the filters:

services.AddMvc(setup => { /* ... */ setup.Filters.Add<ExceptionFilter>(); });
like image 63
Camilo Terevinto Avatar answered Oct 02 '22 16:10

Camilo Terevinto


You don't need to move your logic to an exception filter.

You can simply re-throw the exception received from the IExceptionHandlerFeature you used (IExceptionHandlerFeature/IExceptionHandlerPathFeature)

For example:

var exceptionFeature = context.Features.Get<IExceptionHandlerFeature>();
throw exceptionFeature.Error;

Then your DeveloperExceptionPage will catch the exception down the pipeline.

like image 24
SpiritBob Avatar answered Oct 02 '22 15:10

SpiritBob