zoukankan      html  css  js  c++  java
  • 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());
            }
        }
  • 相关阅读:
    状态压缩DP------学习小记
    hdu 4681 string
    poj 3254 Corn Fields
    poj 3680 Intervals
    poj 1149 pigs ---- 最大流
    最大流算法----(SAP 和 EK)
    poj 2151 Check the difficulty of problems
    FTP的PORT(主动模式)和PASV(被动模式)
    json.stringify(),json.stringify()与json.parse()的区别
    css 选择器
  • 原文地址:https://www.cnblogs.com/guokun/p/5843751.html
Copyright © 2011-2022 走看看