Skip to main content
3 of 8
added exceptions
Hos
  • 884
  • 10
  • 21

Error messages in background job

I am creating a custom command and want to handle exceptions in a userfriendly way, i.e. display an errormessage.

This is the code for my command:

public class ImportCommand : Command
{
    private readonly ICommandArgFactory _commandArgFactory;

    public ImportCommand(ICommandArgFactory commandArgFactory)
    {
        if (commandArgFactory == null) throw new ArgumentNullException(nameof(commandArgFactory));
        _commandArgFactory = commandArgFactory;
    }

    public override void Execute(CommandContext context)
    {
        NameValueCollection parameters = _commandArgFactory.GetArgs(context);

        Sitecore.Context.ClientPage.Start(this, "Import", new ClientPipelineArgs(parameters));
    }

    private void Import(ClientPipelineArgs args)
    {
        if (args.IsPostBack)
        {
            if (args.Result == "no") return;

            ProgressBox.Execute("Import", "Import", DoImport, args);
            SheerResponse.Alert("Import done!");
        }
        else
        {
            SheerResponse.Confirm("Are you sure?");
            args.WaitForPostBack();
        }
    }

    private void DoImport(object[] parameters)
    {
        BaseJob job = Sitecore.Context.Job;

        try
        {
            ClientPipelineArgs args = parameters[0] as ClientPipelineArgs;

            job.Status.State = JobState.Running;
            ...code here...
            job.Status.AddMessage("Parsing some more...");
            job.Status.State = JobState.Finished;
        }
        catch (CustomException ex)
        {
            Log.Error(mcxmfe.Message, this);
            job.Status.State = JobState.Finished;
            Sitecore.Context.ClientPage.SendMessage(this, mcxmfe.Message);
        }
        catch (Exception ex)
        {
            Log.Error(ex.Message, this);
            job.Status.State = JobState.Finished;
        }
    }
}

However, when my CustomException gets thrown, the code that I was hoping would print an error message in a popup also throws an error:

Sitecore.Context.ClientPage.SendMessage(this, mcxmfe.Message);

I've tried using SheerResponse.Alert(...) but that gives a NullReferenceException with the following stactrace:

   at Sitecore.Web.UI.Sheer.ClientPage..ctor(HttpContextBase httpContext)
   at Sitecore.Context.get_ClientPage()
   at Sitecore.Web.UI.Sheer.SheerResponse.Alert(String text, String[] arguments)
   at [CustomCode]

Sitecore.Context.ClientPage.ClientResponse(...) but neither of those work.

How do I show an alert, when the exception is thrown in a background task?

Hos
  • 884
  • 10
  • 21