In previous post you have seen how we can handle exception inside action method

Exception Handling in ASP.NET MVC - Using Action Method

 

Advantage - custom error handling can be done for particular action method.

Disadvantage - We need to repeat code (try… catch block) in every action.


That's why it is good to handle exceptions at application level, so that will write code once  use it for all pages.

In order to do that you have to add Application_Error() function definition in Global.aspx as follows, this is just an example.

 

protected void Application_Error()

 

       {

           Exception unhandledException = Server.GetLastError();

           int httpCode = 0;

 

           // Handle HTTP errors

           if (unhandledException.GetType() == typeof(HttpException))

           {

               HttpException httpException = unhandledExceptionas HttpException;

 

               if (httpException  == null)

 

               {

                   Exception innerException = unhandledException.InnerException;

                   httpException = innerException as HttpException;

               }

 

               if (httpException != null)

 

               {

                   httpCode = httpException .GetHttpCode();

                   switch (httpCode )

                   {

                       case (int)HttpStatusCode.Unauthorized:

                            Response.Redirect("/Http/Error401");

                            break;

                       case 400:

Response.Redirect("~/HTTP404Error.aspx");

                      break;

                       default: Response.Redirect("~/");                             

break;

                   }

               }

           }

 

           // Log the exception and notify system operators

 

// You can create Class file e.g. Exception utility to log error details either in database or text file

           //ExceptionUtility.LogException(unhandledException, Request.Url.ToString(), httpCode);

 

           // Clear the error from the server

 

           Server.ClearError();

       }