Exception handling in ASP.NET MVC

Exception handling is the process of handle the occurrence of exceptional conditions requiring special processing and displaying the customized messages or logs. Exception handling is important in any application. In ASP.NET we can handle exceptions in the following two ways:
  • Try-catch-finally block at method level
  • Using Application_Error
In ASP.NET MVC we have a larger list of ways to handle exception such as:
  • Simple way
  • Override “OnException” method
  • Using “HandleError” Attribute
  • Inheriting from “HandleErrorAttribute”
  • Handling HTTP errors
  • Global Error handling in MVC

Simple way
The simplest wayis to use the traditional .NET exception handling style i.e. try and catch block. Now when exception happens catch block gets executed and it redirects to the error view.

But if we use this method then we will not be utilizing MVC exception mechanism properly and completely. In the further sections we will discuss five important ways by which we can utilize MVC provided features for exception handling.

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

Override “OnException” method
n this method we can override the “OnException” event of the controller and set the “Result” to the view name. This view gets invoked when error occurs in this controller. In the below code you can see we have set the “Result” to a view named as “Error”.We have also set the exception so that it can be displayed inside the view.
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)
     };

        }
}


Using “HandleError” Attribute
The other way of handling error is my using “HandleError” attribute. Implementing “HandleError” attribute is a two-step process

public class HomeController : Controller
 {
        [HandleError()]
        public ActionResult SomeError()
        {
            throw new Exception("test");
        }
}

<system.web>
<customErrors defaultRedirect="Error.cshtml" mode="On">
</customErrors>
</system.web>

Inheriting from “HandleErrorAttribute”
One of the biggest drawbacks of all the previous method was reusability. Error handling logic cannot be reused across other controllers.

In order to reuse error handling logic across controller we can inherit from “HandleErrorAttribute”class anddecorate this class as attribute across controller

public class Err : 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)
            };
        }
    }

Handling HTTP errors
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
<system.web>
<customErrors

                  mode="On" defaultRedirect="Error1">
<error statusCode="404" redirect="~/Testing/NoPageFound"/>
</customErrors>
</system.web> 

Global Error handling in MVC
If you wish to do global error handling across your application you can override the “Application_Error” event and do a response.redirect from the global error event. So if the error handling is not done at the controller level it will get propagated to “Global.asax” file

public class MvcApplication : System.Web.HttpApplication
{
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            Server.ClearError();
            Response.Redirect("/Home/Error");
        }
}


Comments

Popular posts from this blog

Email Sending through O365 using OAuth Protocol

IISRESET vs App Pool Recycling ?

Deploy .Net6.0 Web api with docker