Exception handling in Custom workflow activities

Handling exceptions is an important part of any development effort. In the past few months, I’ve run across several instances where exceptions are not being properly handled in custom workflow activities.

Normally, this doesn’t actually cause issues with the workflows in which the custom workflow activities are being used: The workflow step will fail with an exception and the workflow will stop executing.

The Detail tab of the workflow will contain the exception as reported to CRM:

Unhandled Exception: System.Net.WebException: The remote server returned an error: (404) Not Found.
   at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
   at System.Net.WebClient.DownloadData(Uri address)
   at WorkflowActivities.SendFaxFromSpLocationActivity.Execute(CodeActivityContext context) in c:\SourceControl\xRM\Solutions\Custom Plugins\Class1.cs:line 330
   at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
   at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)

 

Unfortunately, this exception does not inform the user or the administrator that the workflow has indeed failed.

When you look at the list of workflows or system jobs, what you see is a workflow in a Waiting state. You must open the record to see that it has actually failed, and is not waiting.

The proper way to handle exceptions is to throw a new instance of InvalidPluginExecutionException as shown below:

catch (FaultException<OrganizationServiceFault> ex)
{
    throw new InvalidPluginExecutionException(ex);
}

This will result in the workflow stopping with a status of Failed, which will inform everyone concerned that the workflow encountered an issue.

Leave a Reply 7 comments