WebApi 打个Attribute 统一处理异常

146 篇文章 2 订阅

我们处理异常的时候通常都要写形如以下的代码

try
{
   xxxxx
}
catch(Exception ex)
{
   log.write(ex.Message)
}

前一段时间看杨中科的视频,其中吐糟了 mvc 的管道机制,当然用在web ui 的渲染上这个还不如做个前后端分离,因为用管道和razor视图引擎去做这些看着就很繁琐,并且很重,整个架构都复杂化了,但是作为一些AOP的处理,管道却非常的好用,下面用一个Atrribute异常过滤器来统一的处理异常,那么每次有异常出现就不用写如上的代码去手动捕获了

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http.Filters;

namespace HenryMes.WebApi.App_Start
{
    /// <summary>
    /// 异常处理
    /// </summary>
    public class OnErrorResponseAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(HttpActionExecutedContext context)
        {
            var error = string.IsNullOrEmpty(context.Exception.InnerException?.Message) ? context.Exception.Message : context.Exception.InnerException?.Message;
            Utils.LogHelper.GetInstance().Error($@"/{context.ActionContext.ControllerContext.ControllerDescriptor.ControllerName}/{context.ActionContext.ActionDescriptor.ActionName} : {error}");

            if (context.Exception is NotImplementedException)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            }
            else if (context.Exception is TimeoutException)
            {
                var errorObj = new ErrowMessage() { Result = false, Message = "API调用超时" };
                context.Response = new HttpResponseMessage() { StatusCode = HttpStatusCode.RequestTimeout, Content = new ObjectContent(typeof(ErrowMessage), errorObj, new JsonMediaTypeFormatter(), "application/json") };
            }
            //.....这里可以根据项目需要返回到客户端特定的状态码。如果找不到相应的异常,统一返回服务端错误500
            else
            {
                var errorObj = new ErrowMessage() { Result = false, Message = error };
                context.Response = new HttpResponseMessage() { StatusCode = HttpStatusCode.BadRequest, Content = new ObjectContent(typeof(ErrowMessage), errorObj, new JsonMediaTypeFormatter(), "application/json") };
            }
            base.OnException(context);
        }

        /// <summary>
        /// 
        /// </summary>
        public class ErrowMessage
        {
            /// <summary>
            /// 
            /// </summary>
            public bool Result { set; get; }
            /// <summary>
            /// 
            /// </summary>
            public string Message { set; get; }
        }
    }
}

以上就是一个异常处理的过滤器,下面的Contronlller只用打上一个标签就不用再去写 try catch 了

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [OnErrorResponse]
        public IHttpActionResult Test()
        {
            var aaa = 999;
            var b = 333;
            b = 0;
            var c = aaa / b;
            return null;
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值