Custom error pages on asp.net MVC3

John Louros picture John Louros · Mar 8, 2011 · Viewed 55.9k times · Source

I'm developing a MVC3 base website and I am looking for a solution for handling errors and Render custom Views for each kind of error. So imagine that I have a "Error" Controller where his main action is "Index" (generic error page) and this controller will have a couple more actions for the errors that may appear to the user like "Handle500" or "HandleActionNotFound".

So every error that may happen on the website may be handled by this "Error" Controller (examples: "Controller" or "Action" not found, 500, 404, dbException, etc).

I am using Sitemap file to define website paths (and not route).

This question was already answered, this is a reply to Gweebz

My final applicaiton_error method is the following:

protected void Application_Error() {
//while my project is running in debug mode
if (HttpContext.Current.IsDebuggingEnabled && WebConfigurationManager.AppSettings["EnableCustomErrorPage"].Equals("false"))
{
    Log.Logger.Error("unhandled exception: ", Server.GetLastError());
}
else
{
    try
    {
        var exception = Server.GetLastError();

        Log.Logger.Error("unhandled exception: ", exception);

        Response.Clear();
        Server.ClearError();
        var routeData = new RouteData();
        routeData.Values["controller"] = "Errors";
        routeData.Values["action"] = "General";
        routeData.Values["exception"] = exception;

        IController errorsController = new ErrorsController();
        var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
        errorsController.Execute(rc);
    }
    catch (Exception e)
    {
        //if Error controller failed for same reason, we will display static HTML error page
        Log.Logger.Fatal("failed to display error page, fallback to HTML error: ", e);
        Response.TransmitFile("~/error.html");
    }
}
}

Answer

Darin Dimitrov picture Darin Dimitrov · Mar 8, 2011

Here's an example of how I handle custom errors. I define an ErrorsController with actions handling different HTTP errors:

public class ErrorsController : Controller
{
    public ActionResult General(Exception exception)
    {
        return Content("General failure", "text/plain");
    }

    public ActionResult Http404()
    {
        return Content("Not found", "text/plain");
    }

    public ActionResult Http403()
    {
        return Content("Forbidden", "text/plain");
    }
}

and then I subscribe for the Application_Error in Global.asax and invoke this controller:

protected void Application_Error()
{
    var exception = Server.GetLastError();
    var httpException = exception as HttpException;
    Response.Clear();
    Server.ClearError();
    var routeData = new RouteData();
    routeData.Values["controller"] = "Errors";
    routeData.Values["action"] = "General";
    routeData.Values["exception"] = exception;
    Response.StatusCode = 500;
    if (httpException != null)
    {
        Response.StatusCode = httpException.GetHttpCode();
        switch (Response.StatusCode)
        {
            case 403:
                routeData.Values["action"] = "Http403";
                break;
            case 404:
                routeData.Values["action"] = "Http404";
                break;
        }
    }

    IController errorsController = new ErrorsController();
    var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
    errorsController.Execute(rc);
}