Web API Global Error Handl

这个玩意可以解决项目已经开始了但是没写try catch;临时一个个加又很麻烦。适用于web api 2


1. override Handle 和 logger

using System;
using System.Net.Http;
using System.Web;
using System.Web.Http.ExceptionHandling;
using  ClientPortal.Common.Logging;

namespace ClientPortal.Api.Extensions

{
     class CustomExceptionLogger:ExceptionLogger
    {
        private const string HttpContextBaseKey = "MS_HttpContext";
        public override void Log(ExceptionLoggerContext context)
        {
            // Retrieve the current HttpContext instance for this request.
            HttpContext httpContext = GetHttpContext(context.Request);

            if (httpContext == null)
            {
                return;
            }

            if (context.Exception.TargetSite != null)
            {
                LogHelper2.Log.Error(context.Exception.TargetSite.ReflectedType.FullName, context.Exception.TargetSite.Name,context.Exception.ToString());
            }
            
            // Wrap the exception in an HttpUnhandledException so that ELMAH can capture the original error page.
            //Exception exceptionToRaise = new HttpUnhandledException(message: null, innerException: context.Exception);

            // Send the exception to ELMAH (for logging, mailing, filtering, etc.).
            //ErrorSignal signal = ErrorSignal.FromContext(httpContext);
            //  signal.Raise(exceptionToRaise, httpContext);

        }

        private static HttpContext GetHttpContext(HttpRequestMessage request)
        {
            HttpContextBase contextBase = GetHttpContextBase(request);

            if (contextBase == null)
            {
                return null;
            }

            return ToHttpContext(contextBase);
        }

        private static HttpContextBase GetHttpContextBase(HttpRequestMessage request)
        {
            if (request == null)
            {
                return null;
            }

            object value;

            if (!request.Properties.TryGetValue(HttpContextBaseKey, out value))
            {
                return null;
            }

            return value as HttpContextBase;
        }

        private static HttpContext ToHttpContext(HttpContextBase contextBase)
        {
            return contextBase.ApplicationInstance.Context;
        }
    }
}
下面这个似乎可以不用。 目前还没测试
using System.Text;
using System.Web.Http.ExceptionHandling;


namespace ClientPortal.Api.Extensions
{
     class CustomExceptionHandler: ExceptionHandler
    {
        public override void Handle(ExceptionHandlerContext context)
        {
            string a = "";
        }
    }
}


然后把在WebApiConfig里面写

            // There can be multiple exception loggers. (By default, no exception loggers are registered.)
           config.Services.Add(typeof(IExceptionLogger), new CustomExceptionLogger());

            // There must be exactly one exception handler. (There is a default one that may be replaced.)
            // To make this sample easier to run in a browser, replace the default exception handler with one that sends
            // back text/plain content for all errors.
           config.Services.Replace(typeof(IExceptionHandler), new Extensions.CustomExceptionHandler());

到此为止所有没有写try catch的函数,只要出现http exception都会被如下语句记录


LogHelper2.Log.Error(context.Exception.TargetSite.ReflectedType.FullName, context.Exception.TargetSite.Name,context.Exception.ToString());


logHelper2 是自己写的exception 处理,可以录入到一个文件或者数据库



©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值