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 stacktrace:
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]
I've also tried using Sitecore.Context.ClientPage.ClientResponse(...)
but that also gave me a NullReferenceException
with the following stacktrace:
at Sitecore.Web.UI.Sheer.ClientPage..ctor(HttpContextBase httpContext)
at Sitecore.Context.get_ClientPage()
at [CustomCode]
How do I show an alert, when the exception is thrown in a background task?
SheerResponse.Alert
. Why don't you use the same for exception message?