Monday 19 December 2016

Different techniques to handle Exceptions in ASP.NET MVC


There are many ways to handle exceptions. We will discuss here some of them.

1. Try - Catch Block


public ActionResult SomeError()
{
try
{}
catch(Exception ex)
{return View("Error");}
}

2. By Overriding 'OnException' method.

In this we override the 'OnException' method of controller and specify error page.
public class HomeController : Controller
 {
        protected override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;

     var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");

     filterContext.Result = new ViewResult()
{
                ViewName = "Error",
                ViewData = new ViewDataDictionary(model)
     };

        }
}
and in view we have to use
@Model.Exception;

but this way does not provide code re-usability across multiple controllers.

3. HandleError Attribute

1. we put this attribute on action in controller as below.
public class HomeController : Controller
 {
        [HandleError()]
        public ActionResult SomeError()
        {
            throw new Exception("test");
        }
}
2. Add custom error code in web config.
<system.web>
<customErrors defaultRedirect="Error.cshtml" mode="On">
</customErrors>
</system.web> 

If you want different views for different exception types then modify 'HandleError' attribute as below.
public class HomeController : Controller
{
[HandleError(ExceptionType=typeof(ArithmeticException),View="Arthimetic")]
[HandleError(ExceptionType = typeof(NotImplementedException),View ="Error1")]
public ActionResult SomeError()
{
    
}
}

4. Create separate class Inheriting from 'ErrorHandleAttribute'.

In this way we can use code re-usability concept across all controller. we create separate class that inherit from 'ErrorHandleAttribute' class and then we use this 'Errorclass' as an Attribute for Actions in controllers.
public class ErrorClass : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

            filterContext.Result = new ViewResult()
            {
                ViewName = "Error1",
                ViewData = new ViewDataDictionary(model)
            };
        }
    }

5. Handling Http Errors

There are many error like 'FileNotFound', Http 500 error etc . for these we use customer error in web config.
<system.web>
<customErrors
                  mode="On" defaultRedirect="Error1">
<error statusCode="404" redirect="~/Testing/NoPageFound"/>
</customErrors>
</system.web> 

6. Global Error handling 
We write code in Global.asax file in Application_Error event.
protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            Server.ClearError();
            Response.Redirect("/Home/Error");
        }


1 comment:

Note: only a member of this blog may post a comment.