为什么我捕获了异常却返回了Http code 500
Why is Http code 500 returned although I catch the exception
虽然我的 if 子句是在我的 fiddler 中执行的,但我看到的是 http 错误 500 而不是 404,这是为什么呢?
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
if (context.Exception is ResourceNotFoundException)
{
context.Request.CreateErrorResponse(HttpStatusCode.NotFound, context.Exception.Message);
}
else
{
base.Handle(context);
}
}
}
这是我在 fiddler 响应中得到的:
HTTP/1.1 500 Internal Server Error
Content-Length: 3945
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Wed, 08 Jul 2015 08:14:45 GMT
{"Message":"An error has occurred.","ExceptionMessage":"The Resource could not be found!","ExceptionType":"ErpApplicationEndpoints.ResourceNotFoundException","StackTrace":" at ... Removed for clarity...
您需要在 if 子句中的 ExceptionHandlerContext
对象上设置 Result
属性 而不是 CreateErrorResponse
(这也是不正确的,因为您没有分配创造了 HttpResponseMessage
任何事物)
context.Result = <a-httpactionresult-instance-here>
虽然我的 if 子句是在我的 fiddler 中执行的,但我看到的是 http 错误 500 而不是 404,这是为什么呢?
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
if (context.Exception is ResourceNotFoundException)
{
context.Request.CreateErrorResponse(HttpStatusCode.NotFound, context.Exception.Message);
}
else
{
base.Handle(context);
}
}
}
这是我在 fiddler 响应中得到的:
HTTP/1.1 500 Internal Server Error
Content-Length: 3945
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Wed, 08 Jul 2015 08:14:45 GMT
{"Message":"An error has occurred.","ExceptionMessage":"The Resource could not be found!","ExceptionType":"ErpApplicationEndpoints.ResourceNotFoundException","StackTrace":" at ... Removed for clarity...
您需要在 if 子句中的 ExceptionHandlerContext
对象上设置 Result
属性 而不是 CreateErrorResponse
(这也是不正确的,因为您没有分配创造了 HttpResponseMessage
任何事物)
context.Result = <a-httpactionresult-instance-here>