Custom Errorpage in MVC 4

Custom error in MVC 4

Source: http://thirteendaysaweek.com/2012/09/25/custom-error-page-with-asp-net-mvc-4/


Add the following Application_Error method to my Global.asax:



protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Server.ClearError();
 
    RouteData routeData = new RouteData();
    routeData.Values.Add("controller", "Error");
    routeData.Values.Add("action", "Index");
    routeData.Values.Add("exception", exception);
 
    if (exception.GetType() == typeof(HttpException))
    {
        routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
    }
    else
    {
        routeData.Values.Add("statusCode", 500);
    }
 
    IController controller = new ErrorController();
    controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
    Response.End();
}


What we’re doing here is pretty straight forward. First we get the exception tht caused Application_Error to be invoked. Then we set up a bit of route data that we’ll use later to send the request to an error controller. Next we check the type of exception we’re dealing with. If it’s an HttpException (not found, unauthorized, bad request, etc), then we peel the status code off that exception so we can pass that on to our error controller. Otherwise, if it’s not an HTTP related exception, we know the exception is caused by our code and set the status code to 500 (internal server error). Finally, we create an instance of our controller and fire off a request with our route data.
The controller itself is really simple:
public class ErrorController : Controller
{
    public ActionResult Index(int statusCode, Exception exception)
    {
        Response.StatusCode = statusCode;
        return View();
    }
}

The Index method takes the HTTP status code and the exception that we passed as route data from our Application_Error method. We set the status code of the response so that the response contains the correct status code from the request that caused the error, rather than 200, then we return a view. The view I came up with is:

@model ExceptionError
 
An error was encountered while processing your request
The view receives the exception as a model so you could display further detail. Alternatively, you could add some logic to your controller to return a different view based on the exception or status code.

Comments

Popular posts from this blog

c# console applicaton progress bar with spinner

Paging, sorting and searching in mvc + razor

C# SELF DESTRUCT CONSOLE APP