【发布时间】:2017-06-20 15:34:43
【问题描述】:
我正在使用 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);
}
}
例外情况
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();
}
控制器动作
[HttpGet("object/{guid}")]
public WebMessage Get(Guid guid)
{
throw new NotFoundApiException(string.Format("The object {0} was not found", guid));
//...
我可以看到请求进入了我注册的中间件,但异常没有被捕获,只是像往常一样简单地抛出。
我怀疑是竞态条件或类似情况,实际上我对它们的异步函数了解不多。
有人知道为什么我的异常没有被捕获吗?
编辑通过使用 VisualStudio 继续执行,我可以看到预期的行为:我终于得到了回应。
似乎异常并没有真正被中间件捕获,而是在之后以某种方式处理。
【问题讨论】:
-
今天也开始遇到这个问题。使用相同的中间件甚至无法捕获
Exception。 -
祝你好运,如果你发现了什么,请毫不犹豫地告诉你:) 我也会这样做
标签: c# asp.net asp.net-core