2016-12-27 132 views
0

目前我記錄異常,如下 -異常記錄

public ActionResult Login() 
{ 
     try 
     { 
      throw new Exception("test"); 
     } 
     catch (Exception ex) 
     { 
      LogException(ex); 
     } 
     return View(); 
    } 

我可以得到大約從這裏LogException()方法異常清晰&詳細信息。見如下─

Created on: 27-Dec-2016, 06.34.33 PM 
Type: System.Exception 
Error Description: test 
Source File: ...\Controllers\LoginController.cs 
Method: Login 
Line: 20 
Column: 17 

我試圖在同一個方法 -

public class MyCustomAttribute : FilterAttribute, IExceptionFilter 
{ 
    public void OnException(ExceptionContext filterContext) 
    { 
     Exception ex = filterContext.Exception;    
     LogException(ex) 
    } 
} 

public class MyCustomAttribute : HandleErrorAttribute 
{ 
    public override void OnException(ExceptionContext filterContext) 
    { 
     Exception ex = filterContext.Exception;    
     LogException(ex) 
    } 
} 

我也嘗試過載onException的方法 -

public abstract class BaseController : Controller 
{ 
     public BaseController() {} 

     protected override void OnException(ExceptionContext filterContext) 
     { 
      Exception ex = filterContext.Exception; 
      filterContext.ExceptionHandled = true; 

      LogException(ex); 
     } 
} 

在所有三個abose情況下,我沒有得到有關的信息來源文件,方法,行和列 -

Created on: 27-Dec-2016, 06.44.45 PM 
Type: System.Exception 
Error Description: test 
Source File: 
Method: <BeginInvokeAction>b__1e 
Line: 0 
Column: 0 

這是我的方法記錄exception-

 public static void Create(Exception exception, String rootDirectoryPath) 
     { 
      try 
      { 
       StackTrace st = new StackTrace(exception, true);     
       StackFrame frame = st.GetFrame(st.FrameCount - 1); 
       string fileName = frame.GetFileName(); 
       string methodName = frame.GetMethod().Name; 
       int line = frame.GetFileLineNumber(); 
       int col = frame.GetFileColumnNumber(); 

       //Other code ..... 
      } 
      catch (Exception) 
      { 
       //do nothing.    
      } 
     } 

我的問題是,是否有可能恢復從這些3箱子源文件,方法的行和列的信息?

我不想每次都寫try .. catch..來處理異常。

我聽說過ELMAH & Log4Net。但不確定這些圖書館是否能夠從例外中提供我想要的信息。

很抱歉的長期問題。

回答

0

由於ELMAH能夠很好地完成這項工作,您正在重新發明輪子。你試過了嗎?只需一個Nuget包和一些配置即可完全設置。

您可以從Scot Hanselmanread the tutorial瞭解更多關於它的信息。

+0

那麼,如果我想以我的方式,而不是ELMAH? –

+0

然後,我會建議你檢查他們的源代碼,看看他們是如何做和複製你的代碼:https://github.com/elmah/Elmah –

0

我是OneTrueError的作者,它也負責跟蹤您的例外情況。

解決方案的問題在於,異常過濾器(以及ASP.NET框架調用來調用它)將成爲堆棧跟蹤的一部分,因此從堆棧跟蹤對象獲取框架將無法工作。

另請注意,如果.PDB文件不包括在您的網站在生產中時,您不會得到文件編號。

最常見的方法是記錄exception.ToString(),其中包含堆棧跟蹤中的行號(如果存在PDB文件)。

爲什麼要使用自定義的方法呢​​?