From :
http://www.codeproject.com/Articles/731913/Exception-Handling-in-MVC
Introduction
In this article we will discuss about Exception handling in MVC in detail. If you are completely new to MVC then please read day 1 from our MVC step by step article.
Before we go and start our step by step demo on exception handling lets create a sample demo.
public ActionResult TestMethod() { try { //.... return View(); } catch (Exception e) { //Handle Exception; return View("Error"); } }
protected override void OnException(ExceptionContext filterContext) { Exception e = filterContext.Exception; //Log Exception e filterContext.ExceptionHandled=true; filterContext.Result = new ViewResult() { ViewName = "Error" }; }
In Web.Config simply enable custom error as follows and execute our application.
<customerrors mode="On" />Output
It seems that only step 1 done all the work, but how? We have not specified the error page (view) name anywhere, still in response we get error view whenever error occurs.
Let’s understand how?
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } }
As you can see HandleErrorAttrubute is added to global filter collection.
In Global.asax file in Applicaion_Start RegisterGlobalFilters method is invoked.
It handles all the exceptions raised by all action methods in all the controllers and return error view present inside shared folder.
Now errors raised by all action methods present inside TestingController method will be handled. Other exceptions will be considered as unhandled exceptions.
Add HandleErrorAttribute to Action method as follows,
For that we will make our error view strongly typed view of model System.Web.Mvc.HandleErrorInfo and then as usual using @Model keyword we can access the members. One of the member is Exception object.
For that we will use overloaded version of HandleErrorAttribute constructor as follows.
Some of the above limitations can be overcame by extending the default HandleErrorAttribute as follow.
private bool IsAjax(ExceptionContext filterContext) { return filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest"; } public override void OnException(ExceptionContext filterContext) { if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) { return; } // if the request is AJAX return JSON else view. if (IsAjax(filterContext)) { //Because its a exception raised after ajax invocation //Lets return Json filterContext.Result = new JsonResult(){Data=filterContext.Exception.Message, JsonRequestBehavior=JsonRequestBehavior.AllowGet}; filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); } else { //Normal Exception //So let it handle by its default ways. base.OnException(filterContext); } // Write error logging code here if you wish. //if want to get different of the request //var currentController = (string)filterContext.RouteData.Values["controller"]; //var currentActionName = (string)filterContext.RouteData.Values["action"]; }
This is the one which cannot be handled by neither HandleErroAttribute nor CustomHandleErrorAttribute.
But we can follow the traditional web.config approach as follows.
<customerrors mode="On"> <error statuscode="404" redirect="~/Testing/NoPageFound"> </error></customerrors>
Application_Error is an application level event, we define in the global.asax file. It will be executed whenever there is an unhandled exception in the application.
If this is the point, why we won’t use Application_Error always?
Here are the advantages of HandleError over Application_Error,
Thanks for reading. Hope you have enjoyed reading this article. In case you are interested in any
technical training related to MVC, WCF, Design Patterns, WPF, Angular.js, TFS,UML or BI visit www.sukesh-Marla.comor contact [email protected]
See 600+ above FAQ questions and answers in .NET, C#, ASP.NET, SQL, WCF, WPF, WWF, SharePoint, Design patterns, UML etc.