C# 使用请求/响应模式处理ASP.NET核心Web API异常
我们希望通过请求/响应模式应用全局错误处理。 当前代码如下所示。目标是将自定义响应对象引入全局错误处理调用。这可能吗?请参阅下面的自定义响应对象和全局错误处理示例 当前代码:C# 使用请求/响应模式处理ASP.NET核心Web API异常,c#,.net,api,asp.net-core,.net-core,C#,.net,Api,Asp.net Core,.net Core,我们希望通过请求/响应模式应用全局错误处理。 当前代码如下所示。目标是将自定义响应对象引入全局错误处理调用。这可能吗?请参阅下面的自定义响应对象和全局错误处理示例 当前代码: public async Task<ActionResult<GetAllProductResponse>> Get(ProductRequest productRequest) { try { var products = await ProductAppServi
public async Task<ActionResult<GetAllProductResponse>> Get(ProductRequest productRequest)
{
try
{
var products = await ProductAppService.GetAllProducts();
var response = new GetAllProductResponse { Body = products };
return Ok(response);
}
catch (Exception ex)
{
logger.LogError(ex, ex.Message);
var response = new GetAllProductResponse { HasError = true, Error = ex.Message };
return StatusCode(StatusCodes.Status500InternalServerError, response);
}
}
public class GetAllDepartmentResponse : BaseRequestResponse<IEnumerable<ProductDto>>
{
}
public class BaseRequestResponse<T>
{
[Required, ValidateObject]
public T Body { get; set; }
public bool HasError { get; set; }
public string Error { get; set; }
}
另一个资源:
你不能。好吧,你可以,但它很乱 您有两种类型的自定义错误,客户机希望能够解析这两种错误,以及无错误的响应 显然,在客户端进行反序列化时,您可能会失败 通常,您会检查httpcode,如果不是200,您就知道应该反序列化错误对象。您可以尝试第一种样式,如果有问题,可以尝试第二种样式。但这不是一个好办法 最好去掉一种自定义错误格式 您的控制器错误处理是这两个错误中最糟糕的一个。如果您有使用相同身份验证的依赖项,则它不会传递错误代码(如401)
但更严重的是,包装器只是混淆了客户端必须检查的内容,以查看响应是否良好。让客户端在服务器返回异常时引发异常。不要将其全部封装在自定义对象中,让调用代码have
if(response.IsError){throw..}
到处乱扔没错,也许我会让自定义错误模型接受泛型类型T?这能解决问题吗?感谢现在的测试,您已经准备好使用通用的。只需去掉控制器中的所有异常处理。工作完成
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
var code = HttpStatusCode.InternalServerError; // 500 if unexpected
if (ex is MyNotFoundException) code = HttpStatusCode.NotFound;
else if (ex is MyUnauthorizedException) code = HttpStatusCode.Unauthorized;
else if (ex is MyException) code = HttpStatusCode.BadRequest;
var result = JsonConvert.SerializeObject(new { error = ex.Message });
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
}