【问题标题】:Web API generic error handlingWeb API 通用错误处理
【发布时间】:2017-02-20 11:22:32
【问题描述】:

使用 MVC API,如果我们在 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 的调用。

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

【问题讨论】:

  • 如果您只想处理异常,最好的选择可能是自定义异常过滤器。

标签: c# asp.net-web-api error-handling


【解决方案1】:

最好使用下面的通用错误属性过滤器:

 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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-23
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    相关资源
    最近更新 更多