1

I have met some 502 error and how can I make a client robust against 5XX errors by retrying the request once or twice if you receive one, that way even if they do occur, your software will continue running normally.

My codes are here http://pastebin.com/YHpZQ9Z9

1 Answer 1

3

You need to do something like:

try:
    # code that can potentially throw a 502
except HTTPError as e:
    if e.code == 502:
        #put your retry logic here
    else
        print 'Failure: ' + str(e.reason)

For more information, read the urllib2.HTTPError docs.

Sign up to request clarification or add additional context in comments.

3 Comments

the error did not return 502, it return invalid JSON format. As I call from the API it return the JSON data. How can I make sure that I can call the method again when it reach the error ?
Could you elaborate? Is it that the API you call returned you an invalid JSON content and NOT an HTTP 502 error? If that is the case, then you would want to validate the response for ensuring that the API fetched the correct data - there is a reference link: alexconrad.org/2011/10/json-validation.html; however I have not tried the steps within the article. Having said this, it is still always a good practice to try-except on HTTP errors and print a meaningful information to the user
when the api return when calling is suppose to return JSON, and it gave me a JSON error, that it cannot find any JSON format to read. This is because of the HTTP 502 error that return "cannot get key". Thats how the http 502 error comes in. Basically is they return cannot get key my code cannot detect JSON. Is there any way to let it run again to check for API ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.