2017-02-20 45 views
0

使用MVC API,如果我们的API控制器中抛出一个错误的Web API通用的错误处理

public HttpResponseMessage GetError(int id) 
    { 
      int number1 = 3000; 
      int number2 = 0; 

      var t = number1/number2; 

    } 

我们希望我们的deligatingHandler

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
message = base.SendAsync(request, cancellationToken); 
if (!message.Result.IsSuccessStatusCode) 
      { 
       Log.Error(xxxxxxx) 
      } 
} 

检查所有属性中捕获此错误的消息,它只显示通用错误消息,而不是控制器抛出的错误。

Log.Error(xxxxX) 

是我们对log4net的调用。

有没有办法将这个错误传递给处理程序?还是有更好的方法来实现这一目标?

+1

如果你只想做一些不同之处,你最好的赌注可能是一个自定义的异常过滤 – yaakov

回答

0

这是更好地使用通用的错误属性过滤象下面这样:

public class ExceptionHandlingAttribute : ExceptionFilterAttribute 
    { 
     public override void OnException(HttpActionExecutedContext context) 
     { 

// log your error here 
      Log.Error(context.Exception); 

      throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) 
      { 
       Content = new StringContent("An error occurred, please try again or contact the administrator."), 
       ReasonPhrase = "Critical Exception" 
      }); 
     } 

,并在您WebApiConfig类一样进行注册:

config.Filters.Add(new ExceptionHandlingAttribute());