Skip to content
This repository was archived by the owner on Dec 8, 2018. It is now read-only.
This repository was archived by the owner on Dec 8, 2018. It is now read-only.

Preserving the original exception with multiple exception handlers #248

Closed
@gustafsonk

Description

@gustafsonk

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.

// TODO: Optional re-throw? We'll re-throw the original exception by default if the error handler throws.

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions