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?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With