捕捉處理全局異常
自定義一個Attribute
繼承默認的HandleErrorAttribute
namespace EmpowerApiService.Filter
{
public class CustomerErrorAttribute : HandleErrorAttribute
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled) { return; }
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var error = new {
message = filterContext.Exception.Message,
hresult = filterContext.Exception.HResult.ToString("X")
} ;
if (filterContext.HttpContext != null && filterContext.HttpContext.Request != null)
{
var requestUrl = filterContext.HttpContext.Request.Url.ToString();
var requestParams = filterContext.HttpContext.Request.Params;
var requestParamsStr = HttpUtility.UrlDecode(requestParams.ToString());
//
logger.Error(
filterContext.Exception,
"url: {0}, params: {1}",
new Object[] {requestUrl, requestParamsStr });
}
filterContext.ExceptionHandled = true;
// request side error
if (filterContext.Exception is ArgumentException)
{
filterContext.HttpContext.Response.StatusCode = 400;
}
// server side error
else
{
filterContext.HttpContext.Response.StatusCode = 500;
}
// build http response
filterContext.Result = new JsonResult() { ContentType = "applicaltion/json", ContentEncoding = System.Text.Encoding.UTF8, Data = error, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}
註冊自定義的處理類,使之生效,替換默認的錯誤處理,修改APP_Start
中的FilterConfig.cs
namespace EmpowerApiService
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute());
filters.Add(new EmpowerApiService.Filter.CustomerErrorAttribute());
}
}
}
在需要使用錯誤處理的Controller
或Action
上使用特性,就可以捕捉並處理異常
using EmpowerApiService.Filter;
namespace EmpowerApiService.Controllers{
[CustomerError]
public class xxxController : Controller{ ... }
}
使用日誌組件 NLog
先從Nuget
安裝NLog,網文說要同時安裝NLog.Config
,經實測不安裝也可以,測試版本是5.2.3
右鍵點擊目標項目,新增項,選擇新增配置文件
,起名NLog.config
編輯文件如下
<?xml version="1.0"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd"
autoReload="true"
throwException="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<variable name="appName" value="EmpowerApiService" />
<targets>
<target name="logfile"
xsi:type="File"
fileName="${basedir}/logs/${appName}-${shortdate}.log"
layout="${longdate}|${uppercase:${level}}|${message}${newline}${callsite}(${callsite-filename:includeSourcePath=False}:${callsite-linenumber})|${exception:format=ToString}"
maxArchiveFiles="999"
archiveFileName="${basedir}/logs/${appName}-${shortdate}-${###}.log"
createDirs="true"
archiveAboveSize="5242880"
archiveEvery="Day"
archiveNumbering="Sequence"
encoding="UTF-8"
>
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile"/>
</rules>
</nlog>
在需要使用日誌的類中實例化日誌組件即可使用