Handling custom error in mvc

In asp.net mvc there is an custom error in web.config like below:

  1. <customErrors mode="On">
  2.  <error statusCode="404" redirect="~/404.html"/>
  3.  </customErrors>

Sometimes you want to redirect the user to your own custom error controller and log the error message. You can handle it! Firstly create your own Error controller:

  1.  public class ErrorController : Controller
  2.     {
  3.         public ActionResult HttpError404()
  4.         {
  5.             return View("HttpError404");
  6.         }
  7.  
  8.         public ActionResult HttpError500()
  9.         {
  10.             return View("HttpError500");
  11.         }
  12.  
  13.         public ActionResult General()
  14.         {
  15.             return View("General");
  16.         }
  17.     }

Secondly you need to handle this controller in higher level in your application, refer to global.asax and create Application_Error method with the following definition:

  1. protected void Application_Error(object sender, EventArgs e)
  2.         {
  3.             Exception exception = Server.GetLastError();        
  4.             Response.Clear();
  5.             HttpException httpException = exception as HttpException;
  6.             RouteData routeData = new RouteData();
  7.             routeData.Values.Add("controller", "Error");
  8.  
  9.             if (httpException != null)
  10.             {
  11.                 switch (httpException.GetHttpCode())
  12.                 {
  13.                     case 404:
  14.                         routeData.Values.Add("action", "HttpError404");
  15.                         break;
  16.                     case 500:
  17.                         routeData.Values.Add("action", "HttpError500");
  18.                         break;
  19.                     default:
  20.                         routeData.Values.Add("action", "General");
  21.                         break;
  22.                 }
  23.             }
  24.  
  25.             routeData.Values.Add("error", exception);
  26.             Server.ClearError();
  27.             Response.TrySkipIisCustomErrors = true;
  28.             IController errorController = new ErrorController();
  29.             errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
  30.         }

Done! Now you can create your own Views of ErrorController and have your handled ErrorController.


Tags: C# Asp.Net MVC


comments powered by Disqus