CrmService.Retrieve throws SoapException if Record does not exist

If you call the CrmService.Retrieve method with a non-existing id parameter, a SoapException is raised instead of simply returning null.

This exception can be handled by specifically catching SoapException and analyzing the exception’s Detail property (source):

BusinessEntity result = null;
  result = crmService.Retrieve(entityName, entityId, new AllColumns());
catch (SoapException sex)
  XmlNode n = sex.Detail.SelectSingleNode("//error//code");
  if (n.InnerText == "0x80040217")
    result = null;
  else throw;            

The Detail property is really an XmlNode which can be queried in XPath using the SelectSingleNode method. Its string representation in case of failed data retrieval looks like this:

    <description>contact With Id = [some guid] Does Not Exist</description>

I tried to verify the “magic” error code 80040217 and found this list of Dynamics CRM 4 Error Codes on MSDN, which states that the error codes can also be found in the SDK file SDK\Server\Helpers\CS\CrmHelpers\ErrorCodes.cs.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: