提问人:Simon Great 提问时间:10/23/2023 最后编辑:Simon Great 更新时间:10/23/2023 访问量:88
如何根据 .NET 7 中的结果集中错误处理?
how to centralize error handling based on results in .net 7?
问:
我曾经在控制流中遇到异常,我可以轻松地编写一个中间件来将问题详细信息添加到响应中。但是现在我正在使用 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);
}
}
答: 暂无答案
评论