How do I ignore/skip/process a HttpWebResponse error and still return the JSON to my code?

1k views Asked by At

I am trying to setup a call to Stripe via C# and their API. I am using the following code to add a new card via a post to their API and use the JSON response to determine next step

(I tried to strip out everything unnecessary)

public static string stripeAPIcall(string customerId, string parameters, string stripeApiKey) {
    using (var stripeAPI = new System.Net.WebClient())
    {
      try
      {
        // set credentials
        stripeAPI.Credentials = new System.Net.NetworkCredential(stripeApiKey, "");

        //Set Headers
        stripeAPI.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
        stripeAPI.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

        return stripeAPI.UploadString("https://api.stripe.com/v1/customers/" + customerId + "/cards, parameters);
    }
    catch (WebException ex)
    {   
        return "error";
    }
  }
}

And this works fine to create a card when there is a success. However, if there is an error, for example

I used Stripes "card_declined" test card number 4000000000000002

The result is a 402 Error with the following JSON structure

{
  "error": {
    "message": "Your card was declined.",
    "type": "card_error",
    "code": "card_declined"
  }
}

Which blows up my C# code because the 402 error returns

System.Net.WebException: The remote server returned an error: (402) Payment Required. at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request) at System.Net.WebClient.UploadString(Uri address, String method, String data) at System.Net.WebClient.UploadString(String address, String data) at ASP.StripeGlobalHelpers.stripeAPIcall(String url, String parameters, String stripeApiKey, Boolean post)

So, how do I ignore/skip/process the 402 error and still return the JSON to my app? I want to be able to tell the user "Your Card was Declined" or whatever other error message I may get from stripe.

If you need any more info, please let me know.

1

There are 1 answers

2
Mikko Viitala On BEST ANSWER

You could use the following exception handler

catch (WebException ex)
{
    var response = ex.Response.GetResponseStream();
    return response == null ? null : new StreamReader(response).ReadToEnd();
}

This would return e.g.

{
  "error": {
    "type": "invalid_request_error",
    "message": "Invalid API Key provided: ftw?!1"
  }
}