Search code examples
sitecoresitecore8glass-mapper

Sitecore 8 throwing null exception when Datasource item does not exist


I am facing the below problem and can't find out how to get around to it.

  1. I have a rendering and its datasource is pointing to an item in the tree.
  2. I publish the rendering but I don't publish the referenced item.
  3. While viewing the page I get an error. [attached is the screen shot of the error i am getting]

enter image description here

I am using glass mapper.

Thanks in advance for your help.


Solution

  • To elaborate jammykam's answer, you can do something like the code below which I have found in this blog

    Config Patch:

    <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
      <sitecore>
        <pipelines>
          <mvc .getrenderer="">
            <processor patch:instead="processor[@type='Sitecore.Mvc.Pipelines.Response.GetRenderer.GetViewRenderer, Sitecore.Mvc']" type="Namespace.To.Sitecore.Pipelines.Response.GetRenderer.GetViewRendererWithItemValidation, Library">
            </processor>
          </mvc>
        </pipelines>
      </sitecore>
    </configuration>
    

    Code:

    public class GetViewRendererWithItemValidation : GetViewRenderer
    {        `
        protected override Renderer GetRenderer(Rendering rendering, GetRendererArgs args)
        {           
            var viewRenderer = base.GetRenderer(rendering, args) as ViewRenderer;
            if (viewRenderer == null)
                return null;
    
            // Ignore item check when in page editor
            // Also this will break if the item for the datasource has been deleted without removing the link.
            if (Context.PageMode.IsPageEditor || Context.PageMode.IsPageEditorEditing)
                return viewRenderer;
    
            // Override renderer to null when there is an unpublished item refererenced by underlying view
            return viewRenderer.Rendering.Item != null && viewRenderer.Rendering.RenderingItem.InnerItem != null
                ? viewRenderer
                : null;
        }
    }