Now a days during ASP.NET MVC
interview questions interviewer revolve around exception handling question.
So in this article we will try to answer it.
In MVC we have many choices by which we can handle
exceptions. Following are the ways to achieve exception handling in MVC: -
public
ActionResult
MyAction()
{
try
{
//....
return
View();
}
catch
(
Exception
e)
{
//Handle Exception;
return
View(
"Error"
);
}
}
-
Using Overriding OnException method of controller class
protectedoverridevoid
OnException(
ExceptionContext
filterContext)
{
Exception
e = filterContext.Exception;
filterContext.Result =
new
ViewResult
()
{
ViewName =
"Error"
};
}
When we use HandleError Attribute we will be get Error view in return automatically whenever exception occurs.
1. In Controller level.
[
HandleError
()]
publicclass
TestingController
:
Controller
{
public
ActionResult
MyAction()
{
//.....
return
View();
}
}
//It will handle all exceptions raised
by every action method in the controller class.
2. In Action Level
[
HandleError
()]
public
ActionResult
MyAction ()
{
//.....
return
View();
}
3. In Global Level
GlobalFilters
.Filters.Add(
new
HandleErrorAttribute
());
//It will handle all exceptions raised
by every action method in the controller class.
- Using Application_Error attribute in Global.asax
protectedvoid
Application_Error()
{
Exception
e = Server.GetLastError();
//Log e
Server.ClearError();
}
Note: We have uploaded a supporting article for our step by step series. It
explains in detail exception handling in ASP.NET MVC. If you are willing to read
more about it, click
here.
We hope all of you 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.com or contact
SukeshMarla@Gmail.com
Also see following video on
ASP.NET MVC interview questions
video in which we will create a simple customer model/class: -