zoukankan      html  css  js  c++  java
  • WebAPI框架里设置异常返回格式统一

    直接上代码

     1     /// <summary>
     2     /// 消息代理处理,用来捕获这些特殊的异常信息
     3     /// </summary>
     4     public class CustomErrorMessageDelegatingHandler : DelegatingHandler
     5     {
     6         protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     7         {
     8             return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) =>
     9             {
    10                 HttpResponseMessage response = responseToCompleteTask.Result;
    11                 HttpError error = null;
    12                 if (response.TryGetContentValue<HttpError>(out error))
    13                 {
    14                     //自定义错误处理
    15                     //error.Message = "这个接口调用出错了";
    16                 }
    17                 if (error != null)
    18                 {   //这是本人创建的一个返回类                 
    19                     var resultMsg = new ResultMsg { StatusCode = (int)StatusCodeEnum.HttpUrlEror, Info =error.MessageDetail  };
    20                     return new HttpResponseMessage { Content = new StringContent(resultMsg.ToJson(), 
    21                         System.Text.Encoding.GetEncoding("UTF-8"), "application/json"), StatusCode = HttpStatusCode.OK };
    22                 }
    23                 else
    24                 {
    25                     return response;
    26                 }
    27             });
    28         }
    29     }

    然后就是注册该cs文件,找到Global.asax文件

    1         protected void Application_Start()
    2         {
    3             AreaRegistration.RegisterAllAreas();
    4             //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    5             //RouteConfig.RegisterRoutes(RouteTable.Routes);
    6             //BundleConfig.RegisterBundles(BundleTable.Bundles);
    7             GlobalConfiguration.Configure(WebApiConfig.Register);
    8             GlobalConfiguration.Configuration.Filters.Add(new ErrorHandler());
    9         }

    最后大功告成,效果:

    1 {
    2   "StatusCode": 404,
    3   "Info": "在控制器“StudyTask”上找不到与该请求匹配的操作。",
    4   "Data": null
    5 }
  • 相关阅读:
    RabbitMQ学习笔记
    常用算法之排序(3)
    常用算法之排序(2)
    常用算法之排序(1)
    MySQL 是怎样运行的:从根儿上理解 MySQL:字符集和比较规则
    springboot整合websocket实现一对一消息推送和广播消息推送
    喜大普奔!GitHub中文版帮助文档上线了!
    趣图:这是拿offer极高的面试经验
    推荐十大经典排序算法,再也不用担心面试了!
    谈谈培训机构的骗局
  • 原文地址:https://www.cnblogs.com/yanglang/p/9451459.html
Copyright © 2011-2022 走看看