Asp.net-Mvc
在 asp.net MVC 中未命中自定義異常過濾器
我有一個自定義異常過濾器,用於擷取我編寫的自定義異常,但由於某種原因,當我拋出異常時,它永遠不會到達過濾器。相反,我只是收到一個錯誤,即我的異常未由使用者程式碼處理。任何人都可以就我應該如何設置這個問題提供一些建議/幫助嗎?相關程式碼如下:
// controller [CustomExceptionFilter] public class SomeController : Controller { public SomeController() { } public ActionResult Index() { SomeClass.SomeStaticMethod(); return View(); } }那是具有 customexception 屬性的控制器
// some class (where exception is being thrown) public class SomeClass { public static void SomeStaticMethod() { throw new MyCustomException("Test"); } }那是拋出異常的類(對於我的測試)(我也嘗試將它直接拋出到控制器上)。
// Custom exception filter (want this to catch all unhandled exceptions) public class CustomExceptionFilter : FilterAttribute, IExceptionFilter { public void OnException(ExceptionContext filterContext) { if (filterContext.Exception.GetType() == typeof(MyCustomException)) { // do stuff } } }那是自定義異常過濾器……當程式碼執行並引發異常時,它永遠不會到達。相反,我得到了上面提到的錯誤。我讀過的所有內容都表明這是設置它的正確方法,但是當我在自定義過濾器中放置斷點時,它永遠不會被擊中……
我在這裡想念什麼?
TIA
一旦你處理了你的錯誤,你需要讓過濾器上下文知道它已經被處理了。像這樣:
filterContext.ExceptionHandled = true;這應該在你的“//做東西”部分。
我已經複製了您的程式碼,並且過濾器被正常呼叫。我所做的唯一不同是我添加了 exceptionHandled 程式碼並在該行添加了我的斷點。