Mvc有提供錯誤攔捷的方法
在Global.asax.vb中加上Application_Error這個方法,只要Server端發生的錯誤,都會進入。
我的作法是在web.config放一個開關,以方便在開發時,可以不用一直寫log檔,也方便處理,並在進入寫完log之後將頁面導到設定好的ErrorPage(ControllerName:Sheard,ActionName:ErrorPage),並將Exception清除(Server.ClearError())
PS.記得要用Try Catch包起來,否則如果在此方法中產生Exception時會造成無窮迴圈
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim isWriteLog = False
Boolean.TryParse(ConfigurationProcess.GetConfigurationParameter("IsWriteLog"), isWriteLog)
Try
If isWriteLog Then
Dim Errormsg = String.Empty
Dim unhandledException = Server.GetLastError()
Response.Clear()
Dim httpException As HttpException = TryCast(unhandledException, HttpException)
Dim systemException As SystemException = TryCast(unhandledException, SystemException)
Errormsg = "發生列外網頁:{0}錯誤訊息:{1}堆疊內容:{2}"
'If systemException IsNot Nothing OrElse String.IsNullOrEmpty(unhandledException.GetBaseException().Message) Then
Errormsg = String.Format(Errormsg,
Request.Path + Environment.NewLine,
unhandledException.GetBaseException().Message + Environment.NewLine,
unhandledException.StackTrace + Environment.NewLine)
Dim route = RouteTable.Routes.GetRouteData(New HttpContextWrapper(System.Web.HttpContext.Current))
Dim controllers = route.Values("controller")
Dim action = route.Values("action")
Dim strPathName = System.Web.HttpContext.Current.Server.MapPath("/Logs/ErrorLog/")
Dim sw As System.IO.StreamWriter
Dim errorFileName = DateTime.Now.ToString("yyyy-MM-dd")
Dim errorTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")
sw = New System.IO.StreamWriter(strPathName & errorFileName & ".txt", True)
sw.WriteLine(errorTime & Errormsg)
sw.Dispose()
Server.ClearError()
Dim routeData = New RouteData()
routeData.Values.Add("controller", "Shared")
routeData.Values.Add("action", "ErrorPage")
routeData.Values.Add("fileName", errorFileName & ".txt")
routeData.Values.Add("errorTime", errorTime)
Dim errorController As IController = New LionGroupCRM.SharedController()
errorController.Execute(New RequestContext(New HttpContextWrapper(Context), routeData))
'End If
End If
Catch ex As Exception
Server.ClearError()
End Try
End Sub
沒有留言:
張貼留言