C# 错误处理中间件捕获永远不会被捕获
我有一个ErrorHandlingMiddleware,看起来像这样:C# 错误处理中间件捕获永远不会被捕获,c#,error-handling,middleware,C#,Error Handling,Middleware,我有一个ErrorHandlingMiddleware,看起来像这样: public class ErrorHandlingMiddleware { private readonly RequestDelegate _next; public ErrorHandlingMiddleware(RequestDelegate next) { this._next = next; } public async Task Invoke(HttpC
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 statusCode = (int)HttpStatusCode.InternalServerError;
if (ex is NotFoundError) statusCode = (int)HttpStatusCode.NotFound;
//else if (ex is MyUnauthorizedException) code = HttpStatusCode.Unauthorized;
//else if (ex is MyException) code = HttpStatusCode.BadRequest;
var error = new AttemptError(statusCode, ex.Message, ex);
context.Response.ContentType = "application/json";
context.Response.StatusCode = statusCode;
return context.Response.WriteAsync(error.ToString());
}
}
services.AddControllers(options => options.Filters.Add(new HttpResponseExceptionFilter()));
我已将此添加到我的初创公司课程中:
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<ErrorHandlingMiddleware>();
app.SeedIdentityServerDatabase();
app.UseDeveloperExceptionPage();
app.UseIdentityServer();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "r3plica Identity Server v1");
c.OAuthClientId("swagger");
c.OAuthAppName("Swagger Api UI");
});
app.UseMvc();
}
因此,我设置了一个测试:
throw new Exception();
它被扔到我的控制器里。当我运行我的应用程序,然后调用抛出该异常的端点时,它确实会进入我的ErrorHandlingMiddleware
的Invoke
方法,但它不会捕获异常,而是进入wait\u next(context)
有人知道我做错了什么吗?如果您在
app.usedeveloperceptionpage()之后调用它,那么您的中间件将正常工作在启动中编码>
说
将对UsedeveloperCeptionPage的调用放在要捕获异常的任何中间件之前
我通过创建一个过滤器解决了这个问题:
public class HttpResponseExceptionFilter : IActionFilter, IOrderedFilter
{
public int Order { get; set; } = int.MaxValue - 10;
public void OnActionExecuting(ActionExecutingContext context) { }
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.Exception == null) return;
var attempt = Attempt<string>.Fail(context.Exception);
if (context.Exception is AttemptException exception)
{
context.Result = new ObjectResult(attempt)
{
StatusCode = exception.StatusCode,
};
}
else
{
context.Result = new ObjectResult(attempt)
{
StatusCode = (int)HttpStatusCode.InternalServerError,
};
}
context.ExceptionHandled = true;
}
}
我不确定错误处理程序的注册是否正确。我注册了我的中间件,就像这个应用一样。使用中间件(typeof(ErrorHandlingMiddleware));。也许你的注册也是正确的。
services.AddControllers(options => options.Filters.Add(new HttpResponseExceptionFilter()));