前言

    主要是记录一下实现的错误日志拦截,可以在拦截器里面控制返回的信息,把错误信息处理后返回给请求端。

代码实战

拦截器

    /// <summary>
    /// 接口异常捕捉过滤器
    /// </summary>
    [attributeusage(attributetargets.all, allowmultiple = false, inherited = true)]
    public class apierrorhandleattribute : exceptionfilterattribute
    {
        public override void onexception(httpactionexecutedcontext actionexecutedcontext)
        {
            base.onexception(actionexecutedcontext);
            actionexecutedcontext.response = getresponse(actionexecutedcontext);
        }

        /// <summary>
        /// 捕捉异常后响应方法
        /// </summary>
        private httpresponsemessage getresponse(httpactionexecutedcontext actionexecutedcontext)
        {
            var requesthost = actionexecutedcontext.actioncontext.request.requesturi.tostring();//当前请求的地址,包括ip加接口地址
            var method = actionexecutedcontext.actioncontext.request.method.tostring();//当前请求是post/get/put/delete ……
            var controller = actionexecutedcontext.actioncontext.actiondescriptor.controllerdescriptor.controllertype.fullname;//当前请求的控制器所在全路径:xxx.webapi.controllers.xxxcontroller
            var action = actionexecutedcontext.actioncontext.actiondescriptor.actionname; //当前请求的方法
            var paramters = actionexecutedcontext.actioncontext.actionarguments; //获取当前请求的参数
            var ip = httpcontext.current.request.userhostaddress;
           
            loghelper.error($"错误信息:url:{actionexecutedcontext.request.requesturi},--参数信息:{paramters.tojson()},--actionexecutedcontext.exception:{actionexecutedcontext.exception.tojson()}");
            var response = new { code = 506, message = $"{actionexecutedcontext.exception.message},url:{actionexecutedcontext.request.requesturi}", ex = actionexecutedcontext.exception };
           
            return jsonhelper.tohttpresponsemessage(response);
        }

    }

工具类方法

    public static class jsonhelper
    {
        /// <summary>
        /// 转化为json格式的httpresponsemessage
        /// </summary>
        public static httpresponsemessage tohttpresponsemessage(object obj)
        {
            string str;
            if (obj is string || obj is char)
            {
                str = obj.tostring();
            }
            else
            {
                str = obj.tojson();
            }
            var result = new httpresponsemessage { content = new stringcontent(str, encoding.getencoding("utf-8"), "application/json") };
            return result;
        }

        /// <summary>
        /// 转化为json字符串,默认的时间格式
        /// </summary>
        /// <param name="obj">要被转化的对象</param>
        /// <returns>json字符串</returns>
        public static string tojson(this object obj)
        {
            return jsonconvert.serializeobject(obj, new jsonserializersettings { referenceloophandling = referenceloophandling.ignore, dateformatstring = "yyyy-mm-dd hh:mm:ss" });
        }
    }