2012-10-29 45 views
2

我已經設置好了,如果拋出了Exception,我可以用我的自定義錯誤頁面顯示它。但在某些情況下,我不想導航到錯誤頁面,但希望它顯示一個簡單的對話窗口。捕獲顯示信息的例外

public ActionResult Page1() 
{ 
    //The custom error page shows the exception, if one was thrown 

    throw new Exception("An exception was thrown"); 

    return View(); 
} 


public ActionResult Page2() 
{ 
    //A dialog should show the exception, if one was thrown 

    try 
    { 
     throw new Exception("An exception was thrown"); 
    } 
    catch(Exception ex) 
    { 
     ViewData["exception"] = ex; 
    } 
    return View(); 
} 

是否有可能有一個CustomAttribute來處理已在控制器操作中引發的異常?如果我在頁面2中添加CatchException,那麼每次發生異常時,是否可以自動執行在ViewData中存儲異常的過程。我沒有很多CustomAttributes的經驗,如果你能幫助我,我會非常感激。

Page2的例子工作得很好,我只是想讓代碼更乾淨,因爲在每個動作(我想要顯示對話框的地方)都嘗試抓取並不是很好。

我使用.NET MVC 4

回答

3

您可以創建一個基控制器,捕獲異常並處理它適合你。 另外,看起來控制器已經有一個機制來爲你做。您必須重寫控制器內的OnException方法。你可以在這裏一個很好的例子: Handling exception in ASP.NET MVC

此外,還有關於如何使用這裏的onException的另一個答案: Using the OnException

通過使用,您的代碼將是清潔的,因爲你不會做很多try/catch塊。

您必須過濾想要處理的異常。像這樣:

protected override void OnException(ExceptionContext contextFilter) 
{ 
    // Here you test if the exception is what you are expecting 
    if (contextFilter.Exception is YourExpectedException) 
    { 
     // Switch to an error view 
     ... 
    } 
    //Also, if you want to handle the exception based on the action called, you can do this: 
    string actionName = contextFilter.RouteData.Values["action"]; 
    //If you also want the controller name (not needed in this case, but adding for knowledge) 
    string controllerName = contextFilter.RouteData.Values["controller"]; 
    string[] actionsToHandle = {"ActionA", "ActionB", "ActionC" }; 

    if (actionsTohandle.Contains(actionName)) 
    { 
     //Do your handling. 
    } 

    //Otherwise, let the base OnException method handle it. 
    base.OnException(contextFilter); 
} 
+0

「since you1」? – CoffeeRain

+0

從覆蓋OnException我不知道我是否想抓住它並顯示一個對話框,或讓它進入錯誤頁面。是否顯示錯誤頁面或對話框取決於操作而不是Exception類型,所以如果異常是NullReferenceException,那麼我不能在OnException中進行檢查,那麼它應該「打擊」。 你能明白我的想法嗎? – LazyTarget

+0

是的,我明白了。這就是爲什麼你必須過濾你想處理的異常。我將編輯代碼以顯示我的意思。 – digaomatias

0

您可以創建異常類的子類,並且抓住它在你的第2

internal class DialogException : Exception 
{} 

public ActionResult Page2() 
{ 
    //This should a dialog if an exception was thrown 

    try 
    { 
     //throw new Exception("An exception was thrown, redirect"); 
     throw new DialogException("An exception was thrown, show dialog"); 
    } 
    catch(DialogException ex) 
    { 
     ViewData["exception"] = ex; 
    } 
    return View(); 
} 
+0

事情是我已經有一些自定義的異常類型,它們具有特定的屬性。所以我不能真正創建一個新的'DialogException'並繼承Exception。 – LazyTarget