You can have a custom processor in the <mvc.renderRendering>
pipelines as below:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<mvc.renderRendering>
<processor patch:after="processor[@type='Sitecore.Mvc.ExperienceEditor.Pipelines.Response.RenderRendering.AddWrapper, Sitecore.Mvc.ExperienceEditor']"
type="YourNamespaceWithClass, YourAssembly" />
</mvc.renderRendering>
</pipelines>
</sitecore>
</configuration>
Then in the code, it will be something as below:
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Mvc.Pipelines.Response.RenderRendering;
using Sitecore.Mvc.Presentation;
public class CheckMissingDatasource : RenderRenderingProcessor
{
public override void Process(RenderRenderingArgs args)
{
if (!this.IsDatasourceValid(args))
return;
//Log error here if datasource is not valid or missing
args.AbortPipeline();
}
private bool IsDatasourceValid(RenderRenderingArgs args)
{
if (this.RequiresDatasource(args.Rendering.RenderingItem.InnerItem))
{
return !this.ContainsDatasource(args.Rendering);
}
return false;
}
private bool RequiresDatasource(Item item)
{
//Get the Datasource of the current item
string str1 = item["Datasource Template"];
if (!string.IsNullOrEmpty(str1))
{
return true;
}
return false;
}
private bool ContainsDatasource(Rendering rendering)
{
ID result;
return !string.IsNullOrEmpty(rendering.DataSource) && ID.TryParse(rendering.DataSource, out result) && PageContext.Current.Database.GetItem(result) != null;
}
}
Note that I haven't yet test the code, and this will execute for your different items when being rendered. You may also add a check in the method Process
to check if you are using the Page Editor/Experience Editor to display an error message to let the user know that there is an invalid or missing datasource.