Web Api 异常处理过滤器

  1. 创建一个类 WebApiExceptionFilterAttribute,继承 ExceptionFilterAttribute, System.Web.Mvc.IExceptionFilter 并实现接口方法
using System.Net;
using System.Net.Http;
using System.Text; 
using System.Web.Http.Filters; 
using Module;
using Newtonsoft.Json;

namespace SuperWebApi.Filter
{
    /// <summary>
    /// 
    /// </summary>
    public class WebApiExceptionFilterAttribute : ExceptionFilterAttribute, IExceptionFilter
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            MessageResult message = new MessageResult();
            message.status = "500";
            message.message = actionExecutedContext.Exception.Message;
            message.isSuccess = false;
            actionExecutedContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(JsonConvert.SerializeObject(message), Encoding.GetEncoding("UTF-8"), "application/json") };

            1.异常日志记录(正式项目里面一般是用log4net记录异常日志)
            //Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "——" +
            //                  actionExecutedContext.Exception.GetType().ToString() + ":" + actionExecutedContext.Exception.Message + "——堆栈信息:" +
            //                  actionExecutedContext.Exception.StackTrace);

            2.返回调用方具体的异常信息
            //if (actionExecutedContext.Exception is NotImplementedException)
            //{
            //    actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            //}
            //else if (actionExecutedContext.Exception is TimeoutException)
            //{
            //    actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.RequestTimeout);
            //}
            //else if (actionExecutedContext.Exception is FormatException)//参数格式错误
            //{

            //}
            //else if (actionExecutedContext.Exception is NullReferenceException) //当一个空对象被引用时运行时引发
            //{

            //}
            //else if (actionExecutedContext.Exception is StackOverflowException) //堆栈溢出
            //{

            //}
            这里可以根据项目需要返回到客户端特定的状态码。如果找不到相应的异常,统一返回服务端错误500
            //else
            //{
            //    actionExecutedContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(actionExecutedContext.Exception.Message, Encoding.GetEncoding("UTF-8"), "application/json") };
            //}

            base.OnException(actionExecutedContext);

        }

    }
}
  1. 为此全局异常处理器进行注册
    特别说明:一旦进行了全局注册,则所有方法出现异常时,过滤器都会生效。
using SuperWebApi.Filter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace SuperWebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务   
            config.Filters.Add(new AuthValidateAttribute());
            config.Filters.Add(new WebApiExceptionFilterAttribute());

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

            //自定义路由
            config.Routes.MapHttpRoute(
                name: "SupperWebApi",
                routeTemplate: "Api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值