Tutorial :In ASP.NET MVC, should OnException be used for application exceptions?


I'm building a small application in ASP.NET MVC. I'm still trying to find my way around some of the design problems that I encounter.

One of them is the use of exceptions. I've built my model so that it throws an exception whenever an object does not exist or is not accessible to the user. I think I made the right choice, in my opinion.

The problem is, what's next? I can either check for the exception in the controller, and redirect to a different view, but that seems to produce a lot of the same pattern in many actions in many controllers.

Or, I can simply avoid checking for the exception and override the OnException method of the controller (or some base controller class that I will use) to deal with it. That would keep all the clutter from my actions.

From the examples that I've found, I can see how HandleError and OnException can be used to log unhandled exceptions (which is a good thing to do) and redirect to a "sorry!" page, but I would like to know your opinion on using the mechanism on less "unforeseen" exceptions.


You should check out the HandleError attribute. You can specify which view should be shown for which exception. ASP.NET MVC HandleError It's MVC-specific and feels much "cleaner" to me than using the event.

In addition to HandleError, I use ELMAH in order to catch and record exceptions.

Personally, I try to get to a point where all generated exceptions are caught at the controller level and not bubbled beyond that. However, [handleerror] does exactly that -- catches the errors and displays a relevant, pretty page to the user.

Edit: Also note that you can specify this on your controller, not just the action.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »