- Exception Handling (1), in ASP.NET MVC --- this article
- Exception Handling (2), in ASP.NET Web API
- Exception Handling (3), in ASP.NET Core MVC
- Exception Handling (4), in ASP.NET Core Web API
- Exception Handling (5), in ASP.NET Summary
- Exception Handling (6), HttpStatusCode
- Exception Handling (7), C# Exception Handling Statements
Introduction
- Try-catch-finally
- Exception filter
- Application_Error event
- Try-catch-finally: Step 3
- Exception filter
- Default: customError mode="On" in Web.Config, Step 1-1
- Associated with [HandleError] attribute): Step 1-2
- Add statusCode in Web.Config: Step 1-3
- Customized (Overriding OnException method)
- Local: Step 2-2
- Global (Associated with attribute): Step 2-1
- Default: customError mode="On" in Web.Config, Step 1-1
- Application_Error event: Step 4
Discussion
- Step 0: Create an ASP.NET MVC application
- Step 1-1: Error handling by default Exception Filter
- Step 1-2: Default Exception Filter, with [HandleError] attribute
- Step 1-3: Default Exception Filter, Handling the 404 Page Not Foud error
- Step 2-1: Error handling by customized Exception Filter Globally
- Step 2-2: Error handling by customized Exception Filter Locally
- Step 3: Error handling by Try-Catch
- Step 4: Error handling by Application_Error event
Step 0 - Create an ASP.NET MVC app
- Start Visual Studio and select Create a new project.
- In the Create a new project dialog, select ASP.NET Web Application (.NET Framework) > Next.
- In the Configure your new project dialog, enter ErrorHandling for Project name > Create.
- In the Create a new ASP.NET Web Application dialog, select MVC > Creat

Step 1-1: Error handling by default Exception Filter
- Right click Controllers > add > controller.
- In the Add New Scaffolded Item dialog, select Empty Controller > Add.
- In the Add Controller dialog, Change ErrorHandlingController for controller name > Add.

<system.web>
<compilation debug="true" targetFramework="4.7.2"/>
<httpRuntime targetFramework="4.7.2"/>
<customErrors mode="On"> </customErrors>
</system.web>
The magic happens that after re-run the app, the page, https://localhost:44318/ErrorHandling, is redirected to a default Error handing page,

- Authorization filters
- Resource filters
- Action filters
- Exception filters
- Result filters


Step 1-2: Default Exception Filter, with [HandleError] attribute
using System;
using System.Web.Mvc;
namespace ErrorHandling.Controllers
{
public class ErrorHandlingController : Controller
{
// GET: ErrorHandling
public ActionResult Index()
{
return View();
}
[HandleError]
[HandleError(ExceptionType = typeof(DivideByZeroException), View = "Error1")]
[HandleError(ExceptionType = typeof(ArgumentOutOfRangeException), View = "Error2")]
public ActionResult Index1()
{
int a = 1;
int b = 0;
int c = 0;
c = a / b; //it would cause exception.
return View();
}
[HandleError(ExceptionType = typeof(DivideByZeroException), View = "Error1")]
[HandleError(ExceptionType = typeof(ArgumentOutOfRangeException), View = "Error2")]
[HandleError] // this will work, go to the default: view = "Error";
public ActionResult Index2()
{
int a = 1;
int b = 0;
int c = 0;
c = a / b; //it would cause exception.
return View();
}
}
}
And in the project view folder, we add another view, named Error1.cshtml,

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
</head>
<body>
<hgroup>
<h1>Error 1.</h1>
<h2>An error occurred while processing your request.</h2>
</hgroup>
</body>
</html>
Now, run the app, the results will be,



Step 1-3: Default Exception Filter, Handling the 404 Page Not Foud error

<system.web>
<compilation debug="true" targetFramework="4.7.2"/>
<httpRuntime targetFramework="4.7.2"/>
<customErrors mode="On">
<error statusCode="404" redirect="~/ErrorPage"/>
</customErrors>
</system.web>
Now, we add a ErrorPage into the app,
- Add a new empty controller as same as above with name ErrorPageController.
- Open the controller class (see below), right click the Index > Add View >
- In the Add New Scaffolded Item dialog, select MVC 5 View > Add.
- In the Add New dialog, keep index for view name > Add.
@{
ViewBag.Title = "Index";
}
<h2>Customized Error Page</h2>
Now, run the app, we have: https://localhost:44318/errorhandling/index3 ==> Customized Error Page

Step 2-1: Error handling by Customized Exception Filter Globally
public class MyExceptionHandler : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
Exception e = filterContext.Exception;
filterContext.ExceptionHandled = true;
filterContext.Result = new ViewResult()
{
ViewName = "Error4"
};
}
}
We add one more action in the ErrorHandling Controller, associated with a registered Exception Filter Attribute [MyExceptionHandler]:
[MyExceptionHandler]
[HandleError(ExceptionType = typeof(DivideByZeroException), View = "Error1")]
[HandleError(ExceptionType = typeof(ArgumentOutOfRangeException), View = "Error2")]
[HandleError] // this will work, go to the default: view = "Error";
public ActionResult Index4()
{
int a = 1;
int b = 0;
int c = 0;
c = a / b; //it would cause exception.
return View();
}
We can also register the global defined exception filter on control level, or even Globle to add: filters.Add(new MyExceptionHandler()); into the File FilterConfig.cs:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
// MVC Add Exception Filter
filters.Add(new MyExceptionHandler());
}
}
Note:
For ASP.NET MVC, there are three configuration files:

We derive an exception filter class from HandleErrorAttribute class, we need to register it in FilterConfig.cs file, add into GlobalFilerCollection.
Run the app, and try this: https://localhost:44318/errorhandling/index4, we get,

Step 2-2: Error handling by Customized Exception Filter Locally
protected override void OnException(ExceptionContext filterContext)
{
string action = filterContext.RouteData.Values["action"].ToString();
Exception e = filterContext.Exception;
filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");
filterContext.Result = new ViewResult()
{
ViewName = "Error3",
ViewData = new ViewDataDictionary(model)
};
}
Note:
Because this is defined locally in controller, no need for register to controller ot action with an attribute.
Run the app, and try this: https://localhost:44318/errorhandling/index4, the local filter will be executed first, then we get Error3 page:

Step 3 - Error handling by Try-Catch
public ActionResult Index5()
{
int a = 1;
int b = 0;
int c = 0;
try
{
c = a / b; //it would cause exception.
}
catch (Exception ex)
{
return View("Error2");
}
finally
{
}
return View();
}

Step 4 - Error handling by Application_Error event
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
Response.Redirect("~/ErrorPage");
}
}
This is the Outermost error handling, if we did not have any error handling this event will catch the unhandled errors, but all other error hadling will be executed before this event.
Note:
This global exception event does not need register anywhere.
Summary
The ASP.NET MVC Exception handling can be categaried by type as,
- Try-catch-finally
- Exception filter
- Default (Associated with [HandleError] attribute)
- Customized (Overriding OnException method)
- Local
- Global (Associated with attribute)
- Application_Error event
- Local
- Try-catch-finally
- Customized local filter (Overriding OnException method)
- Global
- Default Filter (Associated with [HandleError] attribute)
- Customized Global Filter (Overriding OnException method)
- Application_Error event
- Try-catch-finally ==>
- Customized local filter ==>
- Customized Global Filter ==>
- Default Filter ==>
- Application_Error event
- 《Exception Handling In ASP.NET MVC》 --- C-sharpcorner
- 《Exception Handling in MVC》 --- C-sharpcorner
- 《Exception handling in ASP.NET MVC (6 methods explained)》 --- Code Project

Join the conversation! Your thoughts help the community grow.