In ASP.NET MVC we have a larger list of ways to handle exception such as:
- Try-catch-finally
- Overriding OnException method
- Using the [HandleError] attribute on actions and controllers
- Setting a global exception handling filter
- Handling Application_Error event
- Extending HandleErrorAttribute
To begin with, create a new empty ASP.NET MVC application. Add a controller as "ExceptionTestingController". Add a view for Index. Add another view at "Views\Shared" as "Error.cshtml".
For testing purpose we would cause some kind of exception.
try-catch-finallyChange the Index as in the following.
For testing purpose we would cause some kind of exception.
try-catch-finallyChange the Index as in the following.
- public ActionResult Index()
- {
- int a = 1;
- int b = 0;
- int c = 0;
- try
- {
- c = a / b; //it would cause exception.
- }
- catch (Exception ex)
- {
- return View("Error");
- }
- finally
- {
- }
- return View();
- }
Overriding OnException methodFor this, remove the try block from the preceding code. We need to overwrite OnException as in the following:
- public ActionResult Index()
- {
- int a = 1;
- int b = 0;
- int c = 0;
- c = a / b; //it would cause exception.
- return View();
- }
- protected override void OnException(ExceptionContext filterContext)
- {
- string action = filterContext.RouteData.Values["action"].ToString();
- Exception e = filterContext.Exception;
- filterContext.ExceptionHandled = true;
- filterContext.Result = new ViewResult()
- {
- ViewName = "Error"
- };
- }
- string action = filterContext.RouteData.Values["action"].ToString();
There is the problem with this approach that we cannot reuse the exception handling logic across multiple controllers. That is where global error handling is useful.
Using HandleError AttributeThis is a simple way to handle exceptions in MVC. Remove the OnException implementation from the previous code. Use the following procedure to do that.
Step 1
Using HandleError AttributeThis is a simple way to handle exceptions in MVC. Remove the OnException implementation from the previous code. Use the following procedure to do that.
Step 1
Add in web.config under .
Step 2
Step 2
Decorate the action with [HandleError] as:
- [HandleError]
- public ActionResult Index()
- {
- int a = 1;
- int b = 0;
- int c = 0;
- c = a / b; //it would cause exception.
- return View();
- }
- [HandleError]
- [HandleError(ExceptionType = typeof(DivideByZeroException), View = "Error1")]
- [HandleError(ExceptionType = typeof(ArgumentOutOfRangeException), View = "Error2")]
- public ActionResult Index()
- {
- int a = 1;
- int b = 0;
- int c = 0;
- c = a / b; //it would cause exception.
- return View();
- }
In the same way we can decorate our controller with HandleError. This would handle the exception generated from all the actions from a specific controller.
Limitations:
- Does not support logging exceptions.
- Doesn't catch HTTP exceptions other than 500.
- Doesn't catch exceptions that are raised outside controllers.
- Returns an error view even for exceptions raised in AJAX calls.
Setting a global exception handling filter For this we need to ensure that HandleErrorAttribute is added in RegisterGlobalFilters of the FilterConfig file of App_start and registered in Application_Start. No need to decorate our action and controller with [HandleError].
Extending HandleErrorAttributeWe can also create our own Exception Handler by inheriting from HandleErrorAttribute as in the following:
Extending HandleErrorAttributeWe can also create our own Exception Handler by inheriting from HandleErrorAttribute as in the following:
- public class MyExceptionHandler : HandleErrorAttribute
- {
- public override void OnException(ExceptionContext filterContext)
- {
- if (filterContext.ExceptionHandled ||filterContext.HttpContext.IsCustomErrorEnabled)
- {
- return;
- }
- Exception e = filterContext.Exception;
- filterContext.ExceptionHandled = true;
- filterContext.Result = new ViewResult()
- {
- ViewName = "Error2"
- };
- }
- }
- string action = filterContext.RouteData.Values["action"].ToString();
- [MyExceptionHandler]
- public ActionResult Index()
- {
- int a = 1;
- int b = 0;
- int c = 0;
- c = a / b; //it would cause exception.
- return View();
- }
All MVC exception handling techniques discussed till now do not handle HTTP errors like file not found, HTTP 500 error’s etc. For that we need to make an entry of the error action and the error status code as shown in the below config file.
Hide Copy Code
<system.web> <customErrors mode="On" defaultRedirect="Error1"> <error statusCode="404" redirect="~/Testing/NoPageFound"/> </customErrors> </system.web>
No comments:
Post a Comment