如何从WebAPI的异常中获取HttpStatusCode?

3

当捕获异常时,有没有办法获取HttpStatus代码? 异常可能是Bad Request408 Request Timeout419 Authentication Timeout? 如何在异常块中处理此问题?

(注:HttpStatus指的是HTTP状态码)
 catch (Exception exception)
            {
                techDisciplines = new TechDisciplines { Status = "Error", Error = exception.Message };
                return this.Request.CreateResponse<TechDisciplines>(
                HttpStatusCode.BadRequest, techDisciplines);
            }

1
-1 这显然是生成 HttpResponses 的代码,而不是处理它们的代码。 - Aron
2个回答

2

在我的WebAPI控制器中进行错误处理时,我也曾陷入同样的困境。我对异常处理的最佳实践进行了一些研究,最终得出了以下有效的解决方案(希望能帮到你:)

try
{       
    // if (something bad happens in my code)
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("custom error message here") });
}
catch (HttpResponseException)
{
    // just rethrows exception to API caller
    throw;
}
catch (Exception x)
{
    // casts and formats general exceptions HttpResponseException so that it behaves like true Http error response with general status code 500 InternalServerError
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(x.Message) });
}

2
我注意到你正在捕获一个通用的 Exception。你需要捕获一个更具体的异常才能获取它的唯一属性。在这种情况下,尝试捕获 HttpException 并检查其状态码属性。
然而,如果你正在编写一个服务,你可能希望使用 Request.CreateResponse 来报告错误条件。http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling 有更多信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接