c# – How to replace Error. An error occurred while processing your request.

c# – How to replace Error. An error occurred while processing your request.

Thanks to this question I figured out how to do this. The code below is almost the same as the accepted answers. 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)); 
        }
    }
    

c# – How to replace Error. An error occurred while processing your request.

Leave a Reply

Your email address will not be published.