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());
            }
        }
  • 相关阅读:
    YOLOv5实现自定义对象训练与OpenVINO部署全解析
    GMS程序调试指南GMS-Feature-Matcher
    MobileNet V3与Lite R-ASPP 总结
    codevs 3385 拯救Oier(一) Save Oier—first
    喵哈哈村的魔法考试 Round #6 (Div.3) 题解
    POJ 1852 Ants
    加强赛第一轮题解
    喵哈哈村的魔法考试 Round #3 (Div.2)
    python小数据池,代码块的最详细、深入剖析
    比较三个数的大小
  • 原文地址:https://www.cnblogs.com/guokun/p/5843751.html
Copyright © 2011-2022 走看看