【发布时间】:2020-10-27 23:00:23
【问题描述】:
您好,我需要捕获 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 是您的响应模型吗?我的意思是它是你所有 api 的响应结构吗?
-
@Arsalan Valoojerdi 我有一个名为 BaseResponse 的抽象类,它定义了属性“ErrorCode”,从 BaseResponse 继承了多个类用于不同的 api,例如 TestResponse。
-
您可以使用自定义异常并在中间件中捕获它,但您需要在控制器操作的 catch 块中重新抛出。或者将值存储在 HttpContext (
this.HttpContext.Items["my-key"] = "my values";) -
发生异常后是否还有其他数据要发送给客户,或者只是错误代码?
-
@Arsalan Valoojerdi 只有 2 个属性 - 来自 ResponseModel 的错误代码和错误详细信息
标签: c# asp.net-web-api error-handling middleware