【问题标题】:Logging exceptions with Hellang ProblemDetails使用 Hellang ProblemDetails 记录异常
【发布时间】:2021-06-09 14:37:30
【问题描述】:

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

我尝试将 ExceptionHandler 中间件和 Hellang ProblemDetails 中间件一起使用,但它们不能一起使用。如何在使用 Hellang ProblemDetails 时全局记录异常?

【问题讨论】:

    标签: exception .net-core asp.net-core-webapi


    【解决方案1】:

    经过一番阅读,我意识到我不能将 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);
                };
            });
    

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

    【讨论】:

    • 感谢您通过代码示例分享解决方案!
    猜你喜欢
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    相关资源
    最近更新 更多