【问题标题】:ASP.NET Core Web API exception handling with Request/Response Pattern使用请求/响应模式处理 ASP.NET Core Web API 异常
【发布时间】:2019-09-22 02:41:35
【问题描述】:

我们希望通过请求/响应模式应用全局错误处理。 当前代码如下所示。目标是将自定义 Response 对象带入全局错误处理调用。这可能吗?请参阅下面的自定义响应对象,以及全局错误处理示例。

当前代码:

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

}

**目标代码:如何将上面的自定义响应对象与此处的错误处理合并?是否可以?想作为参数对象传入全局错误处理,可以是Product,也可以是Customer,Location等**

ASP.NET Core Web API exception handling

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

另一个资源: https://code-maze.com/global-error-handling-aspnetcore/

【问题讨论】:

    标签: c# .net api asp.net-core .net-core


    【解决方案1】:

    你不能。好吧,你可以,但它很乱。

    您有两种类型的自定义错误,客户端希望能够解析这两种类型,以及非错误响应。

    显然,当您在客户端反序列化时,您可能会简单地失败。

    通常您检查 httpcode,如果它不是 200,您知道要反序列化错误对象。您可以尝试第一种样式,然后尝试第二种样式。但这不是一个好方法。

    最好摆脱一种自定义错误格式。

    您的控制器错误处理是两者中最差的。如果您有一个使用相同身份验证的依赖项,它不会通过诸如 401 之类的错误代码。

    但更严重的是,包装器只会混淆客户端必须检查的内容,以查看响应是否良好。当服务器返回异常时,让客户端抛出异常。不要将其全部包装在自定义对象中,并让调用代码到处乱扔if(response.IsError) { throw..}

    【讨论】:

    • 你是对的,也许我会让我的自定义错误模型接受泛型类型 T?那会解决问题吗?感谢现在测试
    • 你已经在使用泛型了。只需摆脱控制器中的所有异常处理。工作完成
    猜你喜欢
    • 2016-12-02
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多