Question: Handle exception in Web API


Handle exception in Web API

Answers 1
Added at 2016-12-30 17:12

I am calling a Web API from the Web API I am creating. The API I am calling returns the response in XML like

<lab:lab uri="" xmlns:udf="" xmlns:ri="" xmlns:lab="">
<udf:field type="String" name="Account ID">gt</udf:field>

which I am extracting the value of the Account ID and storing it in the string.

Below the code I am using

using (var client_LabURL = new HttpClient())
  ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  Uri Uri_LabURL = new Uri(result_LabURL);
  client_LabURL.BaseAddress = Uri_LabURL;
  client_LabURL.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
  client_LabURL.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray_Clarity));
  var response_LabURL = client_LabURL.GetAsync(Uri_LabURL).Result;
  string responseString_LabURL = response_LabURL.Content.ReadAsStringAsync().Result;
  XDocument new_doc = XDocument.Parse(responseString_LabURL);
  XNamespace ns = "";
  string accountID = new_doc.Descendants(ns + "field").FirstOrDefault(field => field.Attribute("name").Value.Equals("Account ID")).Value;

But sometimes the API doesnt have the field <udf> with Account ID in it.

<lab:lab uri="" xmlns:udf="" xmlns:ri="" xmlns:lab="">

In this scenario I want to create a response like Invalid API Call. So I addded the below code

   if (string.IsNullOrEmpty(accountID))
    return ResponseMessage(Request.CreateResponse(new { error = "Invalid API Call" }));

This doesnot return the response I am expecting when there is not Account ID but instead throws HTTP 500 error. How can I handle this. Any help is greatly appreciaed

Answers to

Handle exception in Web API

nr: #1 dodano: 2016-12-30 19:12

The reason why you get HTTP status 500, is because you have a NullReferenceException exception in your code: you are accessing the Value property on the result of FirstOrDefault method call, which returns null when no element can satisfy the specified condition.

You can try something like:

var accountIdField = new_doc
    .Descendants(ns + "field")
    .FirstOrDefault(field => field.Attribute("name").Value.Equals("Account ID"));

if (accountIdField == null)
    return ResponseMessage(Request.CreateResponse(new { error = "Invalid API Call" }));
Source Show
◀ Wstecz