如何根据 .NET 7 中的结果集中错误处理?

how to centralize error handling based on results in .net 7?

提问人:Simon Great 提问时间:10/23/2023 最后编辑:Simon Great 更新时间:10/23/2023 访问量:88

问:

我曾经在控制流中遇到异常,我可以轻松地编写一个中间件来将问题详细信息添加到响应中。但是现在我正在使用 FleuntResults,不知道如何实现以前的行为。

我想删除每个控制器操作的以下代码:

 if (result.IsFailed)
    {
        var errorMessage = result.Errors.FirstOrDefault()?.Message;

        var details = new ProblemDetails()
        {
            Status = StatusCodes.Status404NotFound,
            Title = "The specified resource was not found.",
            Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4",
            Detail = errorMessage 
        };

        return NotFound(details);
    }

有异常的代码示例:

switch (exception)
    {
        case NotFoundException notFoundException:
            {
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;

                var response = new NotFoundResponseBody(notFoundException.Message);
                var payload = JsonSerializer.Serialize(response);
                return context.Response.WriteAsync(payload);
            }
        default:
            {
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                var response = new { message = exception.Message };
                var payload = JsonSerializer.Serialize(response);
                return context.Response.WriteAsync(payload);
            }
    }
C# .NET REST ASP.net-core 异常

评论

0赞 Good Night Nerd Pride 10/23/2023
看看这个
0赞 Simon Great 10/23/2023
@GoodNightNerdPride 我不明白如何使用它。文档似乎有点不对劲。我没有看到在那里自定义 ProblemDetails 的选项
0赞 Good Night Nerd Pride 10/23/2023
我也不知道。但是我在这里快速浏览了一下,它提供了一些文档来满足您的要求。目前,它只是一个预览功能。还有一个相关的 GitHub 问题,您可以在其中寻求帮助。
0赞 Simon Great 10/23/2023
@GoodNightNerdPride看起来还没有准备好。我试图编写我的自定义中间件,但那里的代码太复杂了,我认为这是矫枉过正。但我仍然想了解您一般如何处理这种操作?无论我们使用 FluentResults 包还是自定义 Result 模式实现都无关紧要
0赞 Ralf 10/23/2023
如果这是您正在使用的某个想法,则从同一存储库中发出问题。特别要注意的是,作者措辞谨慎:“我必须明智地投入时间。同样,您的时间明智地投入到该套餐中吗?

答: 暂无答案