1

I have an exception handling middleware that looks like this:

public class ExceptionHandlerMiddleware : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
    {
        httpContext.Response.Clear();
        httpContext.Response.StatusCode = GetStatusCode(exception);

        await httpContext.Response.WriteAsJsonAsync
        (
            new ProblemDetails
            {
                Title = "An error occurred",
                Detail = GetErrorMessage(exception)
            },
            JsonSerializerOptions.Default,
            "application/problem+json",
            cancellationToken
        );

        return true;
    }

    /* ... Other stuff ... */
}

In my Startup.cs, this is the code that calls UseExceptionHandler (as recommended by .NET documentation):

app.UseExceptionHandler(appError =>
{
    appError.Run(async context =>
    {
        var exceptionHandler = context.RequestServices.GetRequiredService<IExceptionHandler>();
        var exceptionFeature = context.Features.Get<IExceptionHandlerFeature>();

        if (exceptionFeature != null)
        {
            await exceptionHandler.TryHandleAsync(context, exceptionFeature.Error, default);
        }
    });
});

However, I don't understand why this lambda method is required. A breakpoint inside it will never be hit, and the code works exactly the same way if I change it to this:

app.UseExceptionHandler(_ => { });

My questions:

  1. What is the point of having a lambda method when it never seems to run?
  2. Why does app.UseExceptionHandler(); (without even an empty lambda method) throw a runtime error, even though the compiler allows it?

1 Answer 1

3

As documentation linked by you states:

If an exception handler handles a request, it can return true to stop processing. If an exception isn't handled by any exception handler, then control falls back to the default behavior and options from the middleware.

You are returning always true, so you are marking the exception as handled. If you would return false your lambda passed in UseExceptionHandler would be executed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.