【发布时间】: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