Description
From @gustafsonk on Monday, February 15, 2016 12:25:19 PM
There's already a comment in the code for this feature, but I didn't see an issue created for it so I decided to make this one.
My use case is that I want to have different behaviors for exceptions depending on context like the URL, such as returning a JSON response for a failed API request while returning an HTML response for a failed user page request. I also want to use errorHandlingPath behavior on one of the exception handlers so I can have the HTML scenario handled by an MVC controller. Here's what my code relatively looks like:
// these are effectively try-catches so define them in reverse order
app.UseExceptionHandler("/Home/Error");
app.UseExceptionHandler(handler =>
{
handler.Run(async context =>
{
var exception = context.Features.Get<IExceptionHandlerFeature>().Error;
if (context.Request.Path.StartsWithSegments("/api"))
{
context.Response.ContentType = "application/json";
var response = new
{
Error = exception.Message
};
await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
}
else
{
// lose the stack trace, otherwise you could rewrap it in another exception
throw exception;
}
});
});
The current solution I can come up with involves either throwing the exception stored in the Error property and losing the stack trace of the original exception, or wrapping the exception into another one and making sure that's handled properly across the other exception handlers.
It would be nice to be able to say in an exception handler that the exception was not handled and to keep going up the chain until it is handled. Alternatively I would be happy with a way of combining the 2 handlers in my example into 1 handler if it's simple enough.
Copied from original issue: aspnet/Diagnostics#248