C# Code · D365 Error · Dynamics 365 WEB API

{Dynamics CRM WEB API C#} Parse Error Code and Message from HttpResponse

While I was working on Web API C# code, I found that many calls to CRM web api was failing and I could only see status code and reason phrase which was not much helpful.

I knew that CRM web api returns the exact error message in response and verified that too from postman. I needed code to parse the error code and message to know the exact reason of failing of CRM web api call.

Error response format has changed as compared to previous version. Please see below latest format which we will get as a response from CRM Web API when it fails.

“code”: “<This code is not related to the http status code and is frequently empty>”,
“message”: “<A message describing the error>”

C# code to Parse Error Message and Code

using (HttpClient httpClient = new HttpClient())
		        httpClient.BaseAddress = new Uri(Resource);
		        httpClient.Timeout = new TimeSpan(0, 2, 0);
		        httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
		        httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
		            new MediaTypeWithQualityHeaderValue("application/json"));
		        httpClient.DefaultRequestHeaders.Authorization =
		            new AuthenticationHeaderValue("Bearer", _authResult.AccessToken);
		        JObject newAccount = new JObject
		            {"name", "CSharp Testing"},
		            {"telephone1", "211-888-0909"}

		        HttpResponseMessage createResponse =
		            await httpClient.SendAsJsonAsync(HttpMethod.Post, "api/data/v8.2/accounts", newAccount);

		        Guid accountId = new Guid();
		        if (createResponse.IsSuccessStatusCode)
		            string accountUri = createResponse.Headers.GetValues("OData-EntityId").FirstOrDefault();
		            if (accountUri != null)
		                accountId = Guid.Parse(accountUri.Split('(', ')')[1]);
		            Console.WriteLine("Account '{0}' created.", newAccount["name"]);
		           JObject errorObject = JObject.Parse(createResponse.Content.ReadAsStringAsync().Result);
                        Console.WriteLine(errorObject ["error"]["message"].ToString());
                        Console.WriteLine(errorObject ["error"]["code"].ToString());


Key Points –

  1. As you can see once IsSuccessStatusCode is false, It will go to else condition and that is where I am parsing Error Code and Message from HttpResponse object
  2. We could store these error information in Log entity when you are executing batch jobs for CRM

Hope this helps!

2 thoughts on “{Dynamics CRM WEB API C#} Parse Error Code and Message from HttpResponse

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s