Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging exceptions with Hellang ProblemDetails

I'm using Hellang ProblemDetails package in a Web API application using .Net Core 5 and I need to log the exception before sending response back to client.

I tried using ExceptionHandler middleware and Hellang ProblemDetails Middleware together, but they didn't work together. How can I log exception globally while using Hellang ProblemDetails?

like image 994
Gru97 Avatar asked Oct 16 '25 11:10

Gru97


2 Answers

After some reading, I realized I could't use ExceptionHandler middleware and Hellang ProblemDetails together 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 all the information I need before returning response back to client.

like image 181
Gru97 Avatar answered Oct 19 '25 04:10

Gru97


Another option is to configure options.ShouldLogUnhandledException to cover your cases

https://github.com/khellang/Middleware/blob/5d5257ef54d82c902dbf087486365032d4804aac/src/ProblemDetails/ProblemDetailsMiddleware.cs#L119

Example:

options.ShouldLogUnhandledException = (_, ex, d) => d.Status is null or >= 500 || ex is ValidationException;

like image 31
Simopaa Avatar answered Oct 19 '25 04:10

Simopaa