Skip to content

Preserving the original exception with multiple exception handlers #2594

Closed
@aspnet-hello

Description

@aspnet-hello

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.

https://github.com/aspnet/Diagnostics/blob/a03b2dc6b4b540391be189cea2a5a8f75c890b29/src/Microsoft.AspNetCore.Diagnostics/ExceptionHandler/ExceptionHandlerMiddleware.cs#L79

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-middlewareIncludes: URL rewrite, redirect, response cache/compression, session, and other general middlewaresarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templatesenhancementThis issue represents an ask for new feature or an enhancement to an existing onefeature-diagnosticsDiagnostic middleware and pages (except EF diagnostics)

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions