.Net Core webapi expection catch middleware not catch except



我写了一个像这样的全局异常捕获中间件:

public GlobalExceptionCatchMiddleware(RequestDelegate next, ILogger<GlobalExceptionCatchMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
if(ex is CustomException)
{
var result = new ResponseResult
{
message = "" + ex.Message,
code = 200,
success = false
};
AddCors(ref context);
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
}
else
{
_logger.LogError($"System Uncatched error:{ex.StackTrace}");
var msg=TranslateErrorMessage(ex.Message);
var result = new ResponseResult
{
message =   msg,
code = 200,
success = false
};
AddCors(ref context);
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
}

}
}

和我使用actionfilter来检查用户权限:

public class PrivilegeFilterAttribute:ActionFilterAttribute
{
//....
public override async void OnActionExecuting(ActionExecutingContext context)
{
throw new System.Exception("test throw error");
// do something ...
base.OnActionExecuting(context);
}
//....
}

并在启动时使用globalexceptioncatchmiddleware .cs:


app.UseMiddleware<GlobalExceptionCatchMiddleware>(); 
app.UseRouting();
// ...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

抛出的错误没有被中间件捕获,为什么?过滤器和中间件的执行顺序是什么?

最后,我找到了解决方案:只需删除async并将所有await替换为.Result,然后全局异常处理程序可以捕获从动作过滤器抛出的异常。

老实说,我仍然没有找出原因,但至少问题解决了,不是吗?

最新更新