Exception Handling at Page-View Level - Using Action Method-ThingsWeLearned
Will discuss different exception handling mechanisms that will fit to an MVC application - First will start with handling inside Action method.


Introduction

 

Exception handling is crucial part of every application. It is required for logging errors into database or text/log file, very importantly presenting them to the user in a nicely in case of exception.

 

 

When I was working on application I encounter exceptions (e.g. 400, 500 ) but I was not sure of what might have caused it. Thats where I started exploring various approaches of exception handling in ASP.NET MVC.

 

 

In this article we are going to see how we can handle errors inside Action method. There are various approaches of handling exceptions, I will post others as well.

 

 

 

This typical way of handling exceptions, using try...catch block inside action method as follows -

 

 

public ActionResult Index()
{
   try
   {
       //To do - code block processing
   }
   catch (Exception e)
   {
       //Redirect to an error page
       Response.Redirect("URL to the error page");
   }
   return View();
}

When return type of action is JSON you should return a JSON with the exception message and handle it on the client side, as follows-

public JsonResult GetJson()
{
   try
   {
    //To do - code block processing
   }catch (Exception e)
   {
    //Return the exception message as JSON
    return Json(new { error = e.Message });
   }
   return Json("Return data here");
}


Disadvantage of this method is that you have to write try.. catch blocks in every action method.