I have read articles on exception handling in ASP.NET MVC. I want to make sure I am doing right by presenting it briefly. Could anyone please comment.
-
Catch the exceptions in controller actions, if necessary.
[HttpPost] public ActionResult Insert() { try { } catch { //ModelState.Error -> display error msg to the user. } } -
Override the “OnException” method of controller in basecontroller and “log” the exceptions raised in step 1 and other MVC exceptions
-
Logged the global exceptions in application_onerror.
I would definitely recommend ELMaH instead of writing this code yourself, and also over Log4Net for your MVC apps. I personally avoid any exception handling, unless I have a specific functional response to it. In this way, I don’t “eat” any of the errors that an application-wide tool such as ELMaH will handle gracefully for me.
ELMaH also has nice built-in web reporting, and there are third-party tools specifically for ELMaH that can give you statistics, e.g. the most frequent errors.
You might start with a custom error redirect…
…to a controller that is aware you are using ELMaH…
…backed by a view that helps the visitor get the specific error ID to you:
I also notice this is an HttpPost in this example. If you are doing AJAX, then you’ll want to handle errors for those in a unique way. Pick a standard response you can send to browsers that all of your AJAX code handles gracefully. Perhaps by displaying the ELMaH error ID in a javascript alert (as a simple example).
I also handle a few special types of AJAX errors via Global.asax:
HandleErrorAttribute is a nice feature, but it is well-known that there is extra work to use it in conjunction with ELMaH. How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?