How to replace "Error. An error occurred while processing your request."

46,335

Thanks to this question I figured out how to do this. The code below is almost the same as the accepted answer's. The modification handles no HttpExceptions too.

Steps to make it work:

  1. customErrors element in web.config will now be ignored
  2. Paste the method below to your Global.axax.

    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();
        Response.Clear();
    
        var httpException = exception as HttpException;
    
        if (httpException != null)
        {
            string action;
    
            switch (httpException.GetHttpCode())
            {
                case 404:
                    // page not found
                    action = "NotFound";
                    break;
                case 403:
                    // forbidden
                    action = "Forbidden";
                    break;
                case 500:
                    // server error
                    action = "HttpError500";
                    break;
                default:
                    action = "Unknown";
                    break;
            }
    
            // clear error on server
            Server.ClearError();
    
            Response.Redirect(String.Format("~/Errors/{0}", action));
        }else
        {
            // this is my modification, which handles any type of an exception.
            Response.Redirect(String.Format("~/Errors/Unknown")); 
        }
    }
    
Share:
46,335
Andrzej Gis
Author by

Andrzej Gis

Updated on July 30, 2020

Comments

  • Andrzej Gis
    Andrzej Gis over 3 years

    In my Web.config I have.

    <customErrors mode="On" defaultRedirect="~/Errors/Unknown">
      <error statusCode="403" redirect="~/Errors/Forbidden"></error>
      <error statusCode="404" redirect="~/Errors/NotFound"></error>
    </customErrors>
    

    It works fine if I try to open a page that doesn't exist. (It redirects to my custom error page: ErrorsController.NotFound). When an unhandled exception occurs (in this case in LINQ Signle(...)). It doesn't go to ~/Errors/Unknown, but displays default message:

    Error. An error occurred while processing your request.

    How replace it with my ErrorsController.Unknown ?