Skip to content

Instantly share code, notes, and snippets.

@markgibbons25
Created May 22, 2019 06:47
Show Gist options
  • Save markgibbons25/d8ec3b23787cce7993426e74299ba0a3 to your computer and use it in GitHub Desktop.
Save markgibbons25/d8ec3b23787cce7993426e74299ba0a3 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using Sitecore.XConnect;
using Sitecore.XConnect.Client.Configuration;
using Sitecore.XConnect.Operations;
namespace Yours
{
public interface IXdbRequestPerformer
{
void RequestWithRetry(Action<IXdbContext> action);
void RequestWithRetry(Action<IXdbContext> action, string actionMessage);
}
public class XdbRequestPerformer : IXdbRequestPerformer
{
private const int XdbRequestRetriesCount = 5;
public void RequestWithRetry(Action<IXdbContext> action)
{
RequestWithRetry(action, string.Empty);
}
public void RequestWithRetry(Action<IXdbContext> action, string actionMessage)
{
using (var xconnectClient = SitecoreXConnectClientConfiguration.GetClient())
{
for (int index = 0; index < XdbRequestRetriesCount + 1; ++index)
{
try
{
action(xconnectClient);
break;
}
catch (Exception ex)
{
var xdbOperations = xconnectClient?.LastBatch?.Where(x => x.Status == XdbOperationStatus.Failed);
var str = string.IsNullOrEmpty(actionMessage) ? string.Empty : "of '" + actionMessage + "'";
if (ex is XdbUnavailableException || xdbOperations != null && xdbOperations.Any())
{
if (index == XdbRequestRetriesCount)
{
Sitecore.Diagnostics.Log.Error(FormattableString.Invariant(FormattableStringFactory.Create("Request {0} is failed during xDB operation. (Message: {1})", str, ex.Message)), ex, typeof(XdbRequestPerformer));
throw;
}
else
Sitecore.Diagnostics.Log.Warn(FormattableString.Invariant(FormattableStringFactory.Create("Request {0} is failed during xDB operation. Trying to retry {1} time... (Message: {2})", str, (index + 1), ex.Message)), ex, typeof(XdbRequestPerformer));
}
else
{
Sitecore.Diagnostics.Log.Error(FormattableString.Invariant(FormattableStringFactory.Create("Request {0} is failed. Retry will not be performed because the issue is probably caused not during xDB operation... (Message: {1})", str, ex.Message)), ex, typeof(XdbRequestPerformer));
throw;
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment