text: Continue Reading →
  Using the Try...Catch Statement
  Limitation:
  Advantage
  - Handling Application_Error event (Global Error Handling in Mvc)
  Using the Try...Catch Statement
  The simplestwayis 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.
  public ActionResult SomeError()
  {
  try
  {
  return View();
  }
  catch (Exception ex)
  { return View("Error"); }
  }
  Error.cshtml :
  @model System.Web.Mvc.HandleErrorInfo
  @{
  ViewBag.Title = "Error";
  }
  <hgroup class="title">
  <h1 class="error">Error.</h1>
  <h2 class="error">An error occurred while processing your request.</h2>
  </hgroup>
  Limitation:
  Problem with the above approach is we cannot reuse the exception handling logic across multiple action methods.
  Overriding OnException Method
  In 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. in Index.cshtml file:-
  @Model.Exception;
  Advantage
  Now we can share error handling logic across all the actions in a controller
  Limitation:
  Problem with the above approach is we cannot reuse the exception handling logic across multiple controllers. That where global error handling comes to picture.
  Using HandleError Attribute
  The other way of handling error is my using “HandleError” attribute. Implementing “HandleError” attribute is a two-step process:-
  Step 1 :- We need to first decorate the action method with “HandleError” attribute as shown in the below code.
  public class HomeController : Controller
  {
  [HandleError()]
  public ActionResult SomeError()
  {
  throw new Exception("test");
  }
  }
  Step 2:- In the “Web.config” file you need to add the “customErrors” tag and point to the “Error” view as shown in the below “Web.config” code snippet.
  <system.web>
  <customErrors defaultRedirect="Error.cshtml" mode="On">
  </customErrors>
  </system.web>
  In case you want different error views for different exception types you can decorate action method with multiple “HandleError” attribute point to multiple views as per exception types.
  public class HomeController : Controller
  {
  [HandleError(ExceptionType = typeof(ArithmeticException), View = "Arthimetic")]
  [HandleError(ExceptionType = typeof(NotImplementedException), View = "Error1")]
  public ActionResult SomeError()
  {
  }
  }
  Global Error Handling in Mvc.