Sitecore - Custom 500 error page

There's a ton of posts out there showing how to implement a custom 500 error page in Sitecore. However, I am going to propose a new method to accomplish the same, with the possibility to have a content managed error page and a static error page (this method works for multisite implementations).

The scenario is the following, if there's a 500 error we want to display a content managed error page, and if that content managed error page is erroring out as well, we want to display a static error page. Let's see how we can accomplish this.

1. On your web.config add the following: 

 <system.web>  
   <customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">  
     <error statusCode="500" redirect="error.aspx" />  
   </customErrors>  
 </system.web>  

With this, we are basically saying that we do not want a redirection, but instead, the page that is erroring out will have the content of our custom error.aspx. 

2. Let's now create our custom error.aspx:


 <%@ page language="C#" autoeventwireup="true" codebehind="Error.aspx.cs" inherits="Website.error" %>  
 <%if(!string.IsNullOrWhiteSpace(Html)){%>  
   <%=Html%>  
 <% } else { %>  
   STATIC HTML HERE  
 <% } %>  

3. In the code behind (Error.aspx.cs), use the following code:


 public partial class error : System.Web.UI.Page  
   {  
     public string Html;  
     private string _SitecoreErrorUrl = "/500-error";  
     protected void Page_Load(object sender, EventArgs e)  
     {  
       //Set 500 error code  
       Response.StatusCode = 500;  
       Response.StatusDescription = "Internal Server Error";  
       Html = GetHtmlFromSitecoreErrorPage();  
     }  
     private string GetHtmlFromSitecoreErrorPage()  
     {  
       try  
       {  
         var uri = new Uri(Request.Url.ToString());  
         var url = $"{uri.Scheme}{Uri.SchemeDelimiter}{uri.Host}{_SitecoreErrorUrl}";  
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);  
         using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())  
         {  
           if (response.StatusCode != HttpStatusCode.OK)  
           {  
             return string.Empty;  
           }  
           using (Stream receiveStream = response.GetResponseStream())  
           {  
             var readStream = string.IsNullOrWhiteSpace(response.CharacterSet) ? new StreamReader(receiveStream) : new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));  
             return readStream.ReadToEnd();  
           }  
         }  
       }  
       catch (Exception e)  
       {  
         return string.Empty;  
       }  
     }  
   }  

That's it, this code basically allows you to have a content managed version of the error page and as a fallback, a static error page.

Happy Sitecoring!

Comments