嗨,我需要捕获http请求的异常,例如:
[HttpPost("Test")]
public async Task<ActionResult<TestResponse>> Test(TestRequest request)
{
TestResponse result;
try
{
// call 3rd party service
}
catch(exception ex)
{
result.Errorcode = "Mock" // This Errorcode will be used by client side
}
return Ok(result);
}
现在,因为有许多http请求,所以我想使用中间件来全局处理异常,而不是如上所述,在每个http请求中编写try-catch语句。
public class Middleware
{
readonly RequestDelegate next;
public Middleware(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await next(httpContext);
}
catch (Exception ex)
{
// is there a way to pass TestResponse here so I can do result.Errorcode = "Mock"?
}
}
}
我不知道如何在上面我注释掉的情况下使用中间件方法分配错误代码。可能吗?谢谢。 最佳答案
如果我很了解您的要求,建议您这样做:
您不需要访问TestResponse,并且可以在中间件中配置响应。
public class FailResponseModel
{
public FailResponseModel(string errorCode, object errorDetails)
{
ErrorCode = errorCode;
ErrorDetails = errorDetails;
}
public string ErrorCode { get; set; }
public object ErrorDetails { get; set; }
}
public class ExceptionHandlerMiddleware
{
readonly RequestDelegate next;
public Middleware(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await next(httpContext);
}
catch (Exception ex)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
httpContext.Response.ContentType = "application/json";
var response =
JsonConvert.SerializeObject(new FailResponseModel("your-error-code", "your-error-details"));
await httpContext.Response.WriteAsync(response);
}
}
}