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:
- What is the point of having a lambda method when it never seems to run?
- Why does
app.UseExceptionHandler();
(without even an empty lambda method) throw a runtime error, even though the compiler allows it?