gpt4 book ai didi

c# - 异常处理程序中间件未捕获

转载 作者:太空狗 更新时间:2023-10-29 22:21:26 25 4
gpt4 key购买 nike

我正在使用 ASP.NET Core 开发一个 Web API,我正在尝试实现一个自定义错误处理中间件,这样我就可以抛出标准异常,这些异常可以转换为具有适当 HTTP 状态代码的 JSON 响应。

例如,如果我这样做:

throw new NotFoundApiException("The object was not found");

我需要将它转换成:

StatusCode: 404
ContentType: application/json
ResponseBody: {"error": "The object was not found"}

这是我的中间件:

public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;

public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}

public async Task Invoke(HttpContext context)
{
try {
await next(context);
} catch (ApiException ex) {
await HandleExceptionAsync(context, ex);
}
}

private static Task HandleExceptionAsync(HttpContext context, ApiException exception)
{
var result = JsonConvert.SerializeObject(new { error = exception.Message });
context.Response.ContentType = "application/json";
context.Response.StatusCode = exception.httpStatusCode;

return context.Response.WriteAsync(result);
}
}

异常(exception)情况

public class ApiException : System.Exception
{
private int _httpStatusCode = (int)HttpStatusCode.InternalServerError;
public ApiException() { }
public ApiException(string message): base(message) { }

public int httpStatusCode {
get { return this._httpStatusCode; }
}
}
public class NotFoundApiException : ApiException
{
private int _httpStatusCode = (int)HttpStatusCode.BadRequest;
public NotFoundApiException() { }
public NotFoundApiException(string message): base(message) { }
}

启动

public void Configure(/*...*/)
{
loggerFactory.AddConsole();
app.UseMiddleware<ErrorHandlingMiddleware>();
app.UseMvc();
}

Controller Action

[HttpGet("object/{guid}")]
public WebMessage Get(Guid guid)
{
throw new NotFoundApiException(string.Format("The object {0} was not found", guid));
//...

我可以看到请求进入了我注册的中间件,但是异常没有被捕获,只是照常抛出

我怀疑存在竞争条件或类似情况,实际上我对它们的异步函数了解不多。

有人知道为什么我的异常没有被捕获吗?


编辑 通过使用 VisualStudio 继续执行,我可以看到预期的行为:我终于得到了我的回应。
似乎异常并没有真正被中间件捕获,而是在之后以某种方式进行了处理。

最佳答案

我对这个问题的解决方案是删除 Startup.cs 中的 app.UseDeveloperExceptionPage();

关于c# - 异常处理程序中间件未捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44657363/

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