asp.net web api添加统一异常处理

1、自定义异常处理过滤器

 /// <summary>
    /// 自定义异常处理过滤器
    /// </summary>
    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            var exception = actionExecutedContext.Exception;

            if (exception is BusinessException)     //业务异常,一般不需记录日志,直接反馈错误信息至前端
            {
                actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse((HttpStatusCode)exception.HResult, new HttpError(exception.Message));
            }
            else        //未处理异常如数据库访问出错、代码层面异常等,返回错误信息并记录日志
            {
                actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new HttpError("应用程序发生未知错误"));
                Log.Logger.Error("应用程序处理出错:", exception);
            }
        }
    }

2、将异常处理过滤器添加至WebAPI过滤器集合

  public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //config.Formatters.Add(new BsonMediaTypeFormatter());
            //config.Filters.Add(new CustomAuthenticationFilter());
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Filters.Add(new CustomExceptionFilterAttribute());
        }
    }

 

posted @ 2016-09-05 21:54  GUOKUN  阅读(631)  评论(1编辑  收藏  举报