使用 Hellang ProblemDetails 记录异常

Logging exceptions with Hellang ProblemDetails

我在使用 .Net Core 5 的 Web API 应用程序中使用 Hellang ProblemDetails 包,我需要在将响应发送回客户端之前记录异常。

我尝试同时使用 ExceptionHandler 中间件和 Hellang ProblemDetails 中间件,但它们无法一起工作。如何在使用 Hellang ProblemDetails 时全局记录异常?

经过一番阅读,我意识到我不能同时使用 ExceptionHandler 中间件和 Hellang ProblemDetails,因为它们都以自己的方式改变响应并相互影响。

根据文档here,您可以使用 ProblemDetails 包的配置选项之一在更改响应之前执行代码,然后您可以记录所需的所有信息。

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);
            };
        });

在这里,我使用了一个自定义异常,其中包含响应中问题详细信息对象所需的额外字段,并且我使用实例字段来保存异常并在将响应返回给客户端之前记录我需要的所有信息。