简体   繁体   中英

When can IExceptionHandlerPathFeature be null with ExceptionHandlerMiddleware in Asp.Net Core

Microsoft provides this example for the ExceptionHandlerMiddleware here . This is an excerpt:

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        ...

        var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();

        if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
        {
            await context.Response.WriteAsync("File error thrown!");
        }

        ...
    });
});

I cannot quite understand why would they use ?. operator to get the exception? Can this delegate be triggered without IExceptionHandlerPathFeature ? It does not seem logical to have an exception handler without a guaranteed access to exception.

Here is the code and it does not seem possible to have null in there.

In my particular situation, I had a custom error controller with one of the actions:

[Route("Error")]
public IActionResult Error(ErrorViewModel model)
{
    var exceptionDetails = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    model.Code = 500;

    _logger.Error($"The path {exceptionDetails?.Path} threw an exception " +
         $"{exceptionDetails?.Error}");

    return View(nameof(Error), model);
}

IExceptionHandlerPathFeature was null whenever user enters my error page route in the browser mechanically by hand. So I had to put null conditional operator to restrict null reference exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM