Exception handling may be required in any application, whether it is a web application or a Windows Forms application.
ASP.Net MVC has an attribute called "HandleError" that provides built-in exception filters. The HandleError attribute in ASP.NET MVC can be applied over the action method as well as Controller or at the global level. The HandleError attribute is the default implementation of IExceptionFilter. When we create a MVC application, the HandleError attribute is added within the Global.asax.cs file and registered in the Application_Start event.
- public static void RegisterGlobalFilters(GlobalFilterCollection filters)
- {
- filters.Add(new HandleErrorAttribute());
- }
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- RegisterGlobalFilters(GlobalFilters.Filters);
- RegisterRoutes(RouteTable.Routes);
- }
Important properties of HandleError attribute
The HandleError Error attribute has a couple for properties that are very useful in handling the exception.
ExceptionType
Type of exception to be catch. If this property is not specified then the HandleError filter handles all exceptions.
View
Name of the view page for displaying the exception information.
Master
Master View for displaying the exception.
Order
Order in which the action filters are executed. The Order property has an integer value and it specifies the priority from 1 to any positive integer value. 1 means highest priority and the greater the value of the integer is, the lower is the priority of the filter.
AllowMultiple
It indicates whether more than one instance of the error filter attribute can be specified.
Example
- [HandleError(View = "Error")]
- public class HomeController: Controller
- {
- public ActionResult Index()
- {
- ViewBag.Message = "Welcome to ASP.NET MVC!";
- int u = Convert.ToInt32("");
- return View();
- }
- }
HandleError Attribute at Action Method Level,
- [HandleError(View = "Error")]
- public ActionResult Index()
- {
- ViewBag.Message = "Welcome to ASP.NET MVC!";
- int u = Convert.ToInt32("");
- return View();
- }