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.
{
“error”:{
“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"); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _authResult.AccessToken); //Create 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"]); } else { JObject errorObject = JObject.Parse(createResponse.Content.ReadAsStringAsync().Result); Console.WriteLine(errorObject ["error"]["message"].ToString()); Console.WriteLine(errorObject ["error"]["code"].ToString()); } }
Key Points –
- 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
- 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”