1

I'm doing some integration work with an API which returns a HttpStatusCode 429 when you've hit your daily limit. However the Enum HttpStatusCode in the web response object does not contain this code.

Can some one let me know how I can check for this response code?

Here is some code to show what I'm trying to accomplish:

try
{
  //do something
}
catch (WebException webExp)
{
     var response = (HttpWebResponse) webExp.Response;

     //here I want to check status code for too many requests but it is not   in the enum.
    if (response.StatusCode == HttpStatusCode.TooManyRequests) throw webExp;
}
kcis8rm
  • 107
  • 5
  • 12
  • Please post your code so we can suggest an aproach. right now we have no idea how you are calling the api. – Lorien Apr 12 '17 at 15:43
  • Hard to help without a code sample; have you looked at [How to return 429](http://stackoverflow.com/questions/22636602/how-to-return-http-429) and worked backwards. – Mad Myche Apr 12 '17 at 15:47
  • Apologies, I have added a code sample to help explain what I am trying to do. – kcis8rm Apr 19 '17 at 07:11

2 Answers2

0

I have the same problem and I realise a few things while I search for a solution.

  • WebExceptionStatus enum is not equivalent to http status code that the API you call returned. Instead it is a enum of possible error that may occour during a http call.
  • The WebExceptionStatus error code that will be returned when you receive an error (400 to 599) from your API is WebExceptionStatus.ProtocolError aka number 7 as int.
  • When you need to get the response body or the real http status code returned from the api, first you need to check if WebExceptionStatus.Status is WebExceptionStatus.ProtocolError. Then you can get the real response from WebExceptionStatus.Response and read its content.

This is an example:

try
{
    ...
}
catch (WebException webException)
{
    if (webException.Status == WebExceptionStatus.ProtocolError)
    {
        var httpResponse = (HttpWebResponse)webException.Response;
        var responseText = "";
        using (var content = new StreamReader(httpResponse.GetResponseStream()))
        {
            responseText = content.ReadToEnd(); // Get response body as text
        }
        int statusCode = (int)httpResponse.StatusCode; // Get the status code (429 error code will be here)
        return statusCode;
    }

    // Handle other webException.Status errors
}
Lutti Coelho
  • 2,134
  • 15
  • 31
-1

I had the same problem, you can read the response and then look for 429 or too many requests string:

string responseStr = "";
Stream responseStream = webEx.Response.GetResponseStream();
if (responseStream != null)
{
    using (StreamReader sr = new StreamReader(responseStream))
    {
       responseStr = sr.ReadToEnd();
    }
}

if (responseStr.Contains("429") || responseStr.Contains("Too many requests"))
Console.WriteLine("Is 429 WebException ");
Natalie Polishuk
  • 183
  • 1
  • 12