.NET MVC HandleErrorAttribute可自動獲取500錯誤並跳轉Error.cshtml頁面,前提條件webconfig頁面須要在 <system.web>節點中添加<customErrors mode="On"/>。html
首先在App_Start目錄添加類FilterConfigweb
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new CustomHandleErrorAttribute()); } }
而後在Global.asax中註冊ide
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); log4net.Config.XmlConfigurator.Configure(); } }
通常建立項目時這些都會自動建立(固然配置文件須要手動添加),固然能夠建立本身的異常處理類而後再過濾器中添加(替換默認的異常處理類便可),在自定義異常處理類中能夠添加錯誤日誌this
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public class CustomHandleErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { SaveExceptionAndError(filterContext); base.OnException(filterContext); } /// <summary> /// 寫入錯誤日誌 /// </summary> /// <param name="exceptionContext"></param> private void SaveExceptionAndError(ExceptionContext exceptionContext) { string errortime = string.Empty; string erroraddr = string.Empty; string errorinfo = string.Empty; string errorsource = string.Empty; string errortrace = string.Empty; errortime = "發生時間: " + System.DateTime.Now.ToString(); erroraddr = "異常位置: " + exceptionContext.RequestContext.HttpContext.Request.Url.ToString(); errorinfo = "異常信息: " + exceptionContext.Exception.Message; errorsource = "錯誤源:" + exceptionContext.Exception.Source; errortrace = "堆棧信息:" + exceptionContext.Exception.StackTrace; //獨佔方式,由於文件只能由一個進程寫入. System.IO.StreamWriter writer = null; try { lock (this) { // 寫入日誌 string year = DateTime.Now.Year.ToString(); string month = DateTime.Now.Month.ToString(); string path = string.Empty; string filename = DateTime.Now.Day.ToString() + ".log"; path = exceptionContext.RequestContext.HttpContext.Server.MapPath("~/ErrorLogs/") + year + "/" + month; //若是目錄不存在則建立 if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } System.IO.FileInfo file = new System.IO.FileInfo(path + "/" + filename); writer = new System.IO.StreamWriter(file.FullName, true);//文件不存在就建立,true表示追加 writer.WriteLine("用戶IP:" + exceptionContext.RequestContext.HttpContext.Request.UserHostAddress); writer.WriteLine(errortime); writer.WriteLine(erroraddr); writer.WriteLine(errorinfo); writer.WriteLine(errorsource); writer.WriteLine(errortrace); writer.WriteLine("--------------------------------------------------------------------------------------"); //writer.Close(); } } finally { if (writer != null) writer.Close(); } } }
Error視圖修改spa
@model System.Web.Mvc.HandleErrorInfo @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="robots" content="noindex,nofollow"> <title>錯誤</title> <style> .wrap { margin: 150px auto; width: 450px; font-size: 14px; font-family: 'helvetica neue',tahoma,arial,'hiragino sans gb','microsoft yahei','Simsun',sans-serif; background-color: #fff; color: #808080; min-height: 100px; padding-top: 15px } .wrap table { width: 90%; margin: auto } td { text-align: left; padding: 2px 10px; vertical-align: top } td.header { font-size: 22px; padding-bottom: 10px; color: #000; } td.check-info { padding-top: 20px; } a { color: #328ce5; text-decoration: none; } a:hover { text-decoration: underline; } </style> </head> <body> <div class="wrap"> <table> <tr> <td rowspan="5" style=""><img src="~/Content/Images/warning_pic.jpg" alt="warning" width="70px"></td> <td class="header">抱歉!處理你的請求時出錯</td> </tr> <tr> <td id="td_info"> 錯誤信息:@(Model.Exception.InnerException!=null?Model.Exception.InnerException.Message:Model.Exception.Message) </td> </tr> </table> </div> </body> </html>