Skip to content

Instantly share code, notes, and snippets.

@blacktambourine
Created February 1, 2017 07:22
Show Gist options
  • Save blacktambourine/16493f39690b9c312b390dd6e6f35c2d to your computer and use it in GitHub Desktop.
Save blacktambourine/16493f39690b9c312b390dd6e6f35c2d to your computer and use it in GitHub Desktop.
Handle Exceptions with GlassView
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