5

I've used Hellang Middleware for exception handling as the global exception handling mechanism in my MVC application. I've added the following code in the ConfigureServices method in Startup.cs:

services.AddProblemDetails(opts =>
            {
                // Control when an exception is included
                opts.IncludeExceptionDetails = (ctx, ex) =>
                {
                    // Fetch services from HttpContext.RequestServices
                    var env = ctx.RequestServices.GetRequiredService<IHostEnvironment>();
                    return env.IsDevelopment() || env.IsStaging();
                };
                opts.ShouldLogUnhandledException = (ctx, e, d) =>
                {
                    return (d.Status.HasValue && d.Status.Value >= 500);
                };
            });

Also I've added UseProblemDetails() in Configure method.

However I came to know that if am using UseProblemDetails(), then UseExceptionHandler() won't work! Hence I'am not able to figure out a method for navigating user to a common error view page.

Is there any way to redirect users to an error page while sticking on to Hellang Middleware for exception handling and logging ?

3 Answers 3

5

I had a similar problem. I solved it like the following. In this example logging a custom business fault exception:

services.AddProblemDetails(setup =>
{
    setup.Map<FaultException<BusinessFault>>((context, exception) =>
    {
        // resolve logger
        var logger = context.RequestServices.GetRequiredService<ILogger<ProblemDetails>>();

        // log exception to Seq
        logger.LogError(exception, "{@Exception} occurred.", exception);

        // return the problem details map   
        return new ProblemDetails
        {
            Title = exception.Message,
            Detail = exception.Detail.FaultMessage,
            Status = exception.Detail.FaultType.ToHttpStatus(),
            Type = exception.Detail.FaultType.ToString(),
            Instance = exception.Detail.FaultReference
        };
    });
});
4

See the answer here: https://stackoverflow.com/a/40153711/90287

You have to distinguish between the type of request, if it's an API request or a UI request to determine if a problem+details JSON should be returned or if a web page should be returned, respectively.

This is what I do near the top of the Configure method of Startup.cs:

app.UseWhen(context => context.IsApiRequest(), branch =>
{
    branch.UseProblemDetails();
});

app.UseWhen(context => !context.IsApiRequest(), branch =>
{
    branch.UseExceptionHandler("/Home/Error");
});

You can define your own custom HttpContext extension method:

public static class HttpContextExtensions
{
    public static bool IsApiRequest(this HttpContext context)
    {
        return context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)
            || (context.Request.Headers["X-Requested-With"] == "XMLHttpRequest"); // AJAX request
    }
}
4

This is not exactly the answer to your question, but I had a similar issue in a Web API application regarding using ExceptionHandler middleware and Hellang ProblemDetails Middleware and I also came to realize I could't use them both because both change the response in their own way and affect one another.

Based on the documentation here you can use one of the configuration options of the ProblemDetails package to excute code before changing response and there you can log all the information you need.

services.AddProblemDetails(options =>
        {
            options.IncludeExceptionDetails = (context, ex) =>
            {
                var environment = context.RequestServices.GetRequiredService<IWebHostEnvironment>();
                return environment.IsDevelopment();
            };

            options.Map<IdentityException>(exception => new ProblemDetails()
            {
                Title = exception.Title,
                Detail = exception.Detail,
                Status = StatusCodes.Status500InternalServerError,
                Type = exception.Type,
                Instance = exception.ToString()
            });

            options.OnBeforeWriteDetails = (ctx, pr) =>
            {
                //here you can do the logging
                logger.LogError("Exception Occurred!!!!");
                logger.LogError(pr.Detail);
                logger.LogError(pr.Instance);
            };
        });

Here, I use a custom exception with extra fields that are needed for problem details object in response, and I use the Instance field to hold the exception and log it.

2
  • where are you magically getting logger from?
    – Rebecca
    Commented Nov 4, 2021 at 17:34
  • You have access to IServiceCollection here, so you can build ServiceProvider and resolve the logger from DI container.
    – Gru97
    Commented Nov 6, 2021 at 7:47

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.