gpt4 book ai didi

c# - 错误处理中间件捕获永远不会被捕获

转载 作者:行者123 更新时间:2023-12-03 08:43:05 25 4
gpt4 key购买 nike

我有这个看起来像这样的 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());
}
}

并将其添加到 启动类中:
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();

这是扔在我的 Controller 。当我运行我的应用程序,然后调用抛出该异常的终结点时,它确实到达了 InvokeErrorHandlingMiddleware方法,但不是捕获异常,而是转到了 await _next(context)...。

有人知道我在做什么错吗?

最佳答案

如果您在 Startup 中的app.UseDeveloperExceptionPage();之后放置要使用的调用,则中​​间件将起作用。

Handle errors in ASP.NET Core

Place the call to UseDeveloperExceptionPage before any middleware that you want to catch exceptions.

关于c# - 错误处理中间件捕获永远不会被捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59914371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com