【发布时间】:2020-01-25 23:43:56
【问题描述】:
我有这个 ErrorHandlingMiddleware,看起来像这样:
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());
}
}
我已将此添加到我的 Startup 类中:
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();
}
我希望如果我在我的应用程序中的任何地方抛出异常,它会被捕获并执行以下行:
await HandleExceptionAsync(context, ex);
所以,我设置了一个测试:
throw new Exception();
这是在我的控制器中抛出的。当我运行我的应用程序,然后调用引发该异常的端点时,它确实到达了我的ErrorHandlingMiddleware 的Invoke 方法,但是没有捕获到异常,它只是转到await _next(context).. ..
有谁知道我做错了什么?
【问题讨论】:
-
我不确定错误处理程序的注册是否正确。我注册了我的中间件,比如这个 app.UseMiddleware(typeof(ErrorHandlingMiddleware));。也许您的注册也是正确的。
标签: c# error-handling middleware