3

无论如何我们可以在捕获异常时获取 HttpStatus 代码吗?例外情况可能是Bad Request, 408 Request Timeout, 419 Authentication Timeout? 如何在异常块中处理这个?

 catch (Exception exception)
            {
                techDisciplines = new TechDisciplines { Status = "Error", Error = exception.Message };
                return this.Request.CreateResponse<TechDisciplines>(
                HttpStatusCode.BadRequest, techDisciplines);
            }
4

2 回答 2

2

I notice that you're catching a generic Exception. You'd need to catch a more specific exception to get at its unique properties. In this case, try catching HttpException and examining its status code property.

However, if you are authoring a service, you may want to use Request.CreateResponse instead to report error conditions. http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling has more information

于 2013-10-14T16:25:42.237 回答
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) });
}
于 2014-02-14T18:24:03.470 回答