Created
February 1, 2017 07:22
-
-
Save blacktambourine/16493f39690b9c312b390dd6e6f35c2d to your computer and use it in GitHub Desktop.
Handle Exceptions with GlassView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Sitecore.Diagnostics; | |
using Sitecore.Mvc.Presentation; | |
namespace Diversus.Core.Sitecore.ViewRenderers | |
{ | |
public class ExceptionSafeViewRenderer : ViewRenderer | |
{ | |
/// <summary> | |
/// Handle any Exceptions in the mvc rendering. Also handles missing datasources. | |
/// http://www.hhog.com/blog/robust-mvc-rendering-exception-handler/ | |
/// </summary> | |
/// <param name="writer"></param> | |
public override void Render(System.IO.TextWriter writer) | |
{ | |
try | |
{ | |
base.Render(writer); | |
} | |
catch (Exception ex) | |
{ | |
//Handle exception and prevent it from bubbling up | |
Log.Error(string.Format("Failed to process view '{0}'", this.ViewPath), ex, this); | |
Exception innerException = ex.InnerException; | |
//If pagemode is normal then render an html comment with some clues to the problem | |
if (global::Sitecore.Context.PageMode.IsNormal) | |
{ | |
writer.WriteLine("<!-- Exception rendering view '{0}': {1} -->", | |
this.ViewPath, | |
ex.Message); | |
while (innerException != null) | |
{ | |
writer.WriteLine("<!-- Inner Exception: {0} -->", innerException.Message); | |
innerException = innerException.InnerException; | |
} | |
} | |
else | |
{ | |
//In Experience Editor mode, render the exception in a div | |
writer.Write("<div class='view-render-exception'>"); | |
writer.Write("Error rendering view {2}: {0}<br/><pre><code>{1}</code></pre>", | |
ex.Message, | |
ex.StackTrace, | |
this.ViewPath); | |
while (innerException != null) | |
{ | |
writer.Write("<hr/>Inner Exception {0}<br/><pre><code>{1}</code></pre>", | |
innerException.Message, | |
innerException.StackTrace); | |
innerException = innerException.InnerException; | |
} | |
writer.Write("</div>"); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment