Explain Exception Handling in ASP.NET MVC

What is an Exception?

 Exception is an event that occurs during execution of a program it may be any error or unexpected behavior that an application encounters to disrupt normal flow of our application.

What is Exception Handling in Asp.Net MVC?

Exception handling is a mechanism to handle the error occurs during runtime. We use exception handing mechanism to handle the error so that the normal flow of our application can be maintained even if the runtime error occurred.

Exception Handling in ASP.NET MVC

Asp.net provide various method to handle exception

  • Try-catch-finally
  • Overriding OnException method
  • Using the [HandleError] attribute
  • Inheriting HandleErrorAttribute
  • Setting a global exception handling filter
  • Handling Application_Error event
  • Handling HttpErrors

Using Try-catch-finally

public ActionResult Create([Bind(Include = “Id,Enrollment,BookName,Issue_date,Return_date,IsReturn”)] IssueBook issueBook)

{

 

var current_date = DateTime.Today.ToString();

var return_date = DateTime.Today.AddDays(30).ToString();

 

var name = issueBook.BookName.ToString();

SqlCommand cmd = new SqlCommand(“InsertIssueBooks”, con);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue(“@Enrollment”, issueBook.Enrollment);

cmd.Parameters.AddWithValue(“@BookName”, issueBook.BookName.ToString());

cmd.Parameters.AddWithValue(“@Issue_date”, current_date);

cmd.Parameters.AddWithValue(“@Return_date”, return_date);

cmd.Parameters.AddWithValue(“@IsReturn”, false);

 

con.Open();

cmd.ExecuteNonQuery();

}

 

Without exception handling, it generates exception and stop the normal execution of our application.

My procedure name is InsertIssueBook. I have changed my procedure name InsertIssueBooks. So after run the application exception is occurred.

 

[fig :- Exception Occur]

 

With the help of try-catch block

public ActionResult Create([Bind(Include = “Id,Enrollment,BookName,Issue_date,Return_date,IsReturn”)] IssueBook issueBook)

{

try

{

var current_date = DateTime.Today.ToString();

var return_date = DateTime.Today.AddDays(30).ToString();

 

var name = issueBook.BookName.ToString();

SqlCommand cmd = new SqlCommand(“InsertIssueBooks”, con);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue(“@Enrollment”, issueBook.Enrollment);

cmd.Parameters.AddWithValue(“@BookName”, issueBook.BookName.ToString());

cmd.Parameters.AddWithValue(“@Issue_date”, current_date);

cmd.Parameters.AddWithValue(“@Return_date”, return_date);

cmd.Parameters.AddWithValue(“@IsReturn”, false);

 

con.Open();

cmd.ExecuteNonQuery();

}

catch

{

Response.Write(” Something wants to wrong”);

}

}

 

Overriding OnException Method

Another way to handle exceptions in controller level by overriding the OnException() method in the controller class. This method deals with all unhanded errors with error code 500.

OnException method take argument as an object of ExceptionContext that contains all information about the exception that can be used to log. We require to set ExceptionHandled = true. We can handle all the exception generated from specific controller.

public class HomeController : Controller{    public ActionResult Index()    {        string msg = null;        ViewBag.Message = msg.Length;                    return View();    }    protected override void OnException(ExceptionContext filterContext)    {        filterContext.ExceptionHandled = true;        filterContext.Result = RedirectToAction(“Error”, “InternalError”);        filterContext.Result = new ViewResult        {            ViewName = “~/Views/Error/InternalError.cshtml”        };   }}  Using HandleError Attribute In HandleError Attribute we have to enable Custom Error in web.config file. In this method, we can add customErrors under system.web inside the web.config file.   

 

public class HomeController : Controller

{

// GET: Home

public ActionResult Index()

{

return View();

}

} Add following code in Index view

@{

ViewBag.Title = “Home Page”;

}

 

<h2>Home</h2>

@Html.ActionLink(“About Us”, “About”, “Home”)

[Fig:- Index view]

Here I will throw exception in About method to demonstrate HandleError attribute

public ActionResult About()

{

throw new Exception(“Some unknown error encountered!”);

return View();

}

Now run the application some exception are occurs.

[Fig:- Exception Occur]

In Order to prevent yellow screen, we have to add customError in web.config file

<system.web>

<customErrors mode=”On”></customErrors>

</system.web> Add HandleError Attribute on About method.

[HandleError]

public ActionResult About()

{

throw new Exception(“Some unknown error encountered!”);

return View();

} Inside the shared folder click on Error.cshtml modify error message as per your requirement.

<!DOCTYPE html>

<html>

<head>

<meta name=”viewport” content=”width=device-width” />

<title>Error</title>

</head>

<body>

<hgroup>

<h3>An error occurred while processing your request. Please contact the administrator.</h3>

</hgroup>

</body>

</html>

Now run the code saw the following page instead of yellow screen.

[Fig:- Error Page]

You can add one or more HandleError attribute as per your requirement.

 

If you have different error views for different types of exceptions that you can use with action method with multiple “HandleError” attribute with a list of the various types, depending on the type of the exception.

 

[HandleError]

[HandleError(ExceptionType = typeof(SqlException), View = “Error1”)]

[HandleError(ExceptionType = typeof(ArgumentOutOfRangeException)View = “Error2”)

public ActionResult About()

{

throw new Exception(“Some unknown error encountered!”);

return View();

}

 

In the above example, if SqlExceptionOccurs, then it will Show Error1.cshtml error view or if ArgumentOutOfRangeExceptionException occurs, then it will show Error2.cshtml View.

Inheriting HandleErrorAttribute

We can also create our own Exception Handler to reuse error handling logic by inheriting from HandleErrorAttribute class.

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”

};

}

}

 

OnException method take argument as an object of ExceptionContext that contains all information about the exception that can be used to log. We require to set ExceptionHandled = true. We can handle all the exception generated from specific controller.

 

Now we can use our MyExceptionHandler attribute in action method instead of HandleError Attribute

 

[MyExceptionHandler]

public ActionResult About()

{

throw new Exception(“Some unknown error encountered!”);

return View();

}

 

Setting Global Exception Handling Filter

You can use the filter to apply at the global level, int the application_start event in the Global.aspx file by using default FilterConfig.RegisterGlobalFilters() method

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Optimization;

using System.Web.Routing;

 

namespace AJAX

{

public class MvcApplication : System.Web.HttpApplication

{

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes);

BundleConfig.RegisterBundles(BundleTable.Bundles);

}

}

}

 

The [HandleError] filter has been applied globally in the MVC application by default in every MVC application.

using System.Web;

using System.Web.Mvc;

 

namespace AJAX

{

public class FilterConfig

{

public static void RegisterGlobalFilters(GlobalFilterCollection filters)

{

filters.Add(new HandleErrorAttribute());

}

}

}

Handling 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(“/Home/Error”);

}

}

In the Application_Error event handler, it calls the Server.ClearError() so as to convey to ASP.NET that the exception has been handled and there is no longer an exception in the application.

Handling HttpErrors

All MVC exception handling techniques discussed till now do not handle HTTP errors such as file not found, an HTTP 500 error’s, and so on. In order to do this, we need to implement the error and an error status code, as listed in the following web.config file.

<system.web>

<customErrors mode=”On”>

<error statusCode=”404″ redirect=”~/Error/_NotFound” />

<error statusCode=”403″ redirect=”~/Error/_NotFound” />

<error statusCode=”400″ redirect=”~/Error/_NotFound” />

<error statusCode=”500″ redirect=”~/Error/_NotFound” />

</customErrors>

</system.web>

Conclusion

ASP.NET MVC provide various Exception Handling technique at controller level, Action level and global level using various exception handling technique we can continue or normal flow of our application execution.

 

Author Bio: Vinod Satapara – Technical Director, iFour Technolab Pvt. Ltd.

Technocrat and entrepreneur of a reputed Asp.Net Development Company with years of experience in building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and help organization to achieve goals.

Leave a reply:

Your email address will not be published.

Site Footer