0

I have some code that is generating the following response:

The request failed: Google returned a response with code 429.

I can't get any of these if statements to trigger even though I'm printing the err variable so I know exactly what it says. What am I doing wrong here?

try:
    <---irrelevant code--->
except (ResponseError, RuntimeError, TypeError, NameError, KeyError) as err: 
    print("Key error: {}. {}, while querying {} pausing".format(KeyError, err, stock))
    if err == 429:
        print("429 error")
        <---more actions--->
    if err == "The request failed: Google returned a response with code 429."
        print("429 error")
        <---more actions--->
Timus
  • 10,974
  • 5
  • 14
  • 28
  • You say it's generating a "response" - did you mean to say it's "raising an exception." There's a huge difference. A response will be a string and will not be caught by your `except:` logic. – Paul Cornelius Oct 06 '21 at 03:42
  • 1
    I doubt the error message is of int type, you should probably use `'429'` – mozway Oct 06 '21 at 03:43
  • Show a [example]. Especially depends on which library you're using, the way to determine if an error happens and get the status code can be different. – user202729 Oct 06 '21 at 04:29
  • The type of `err` is one the relevant `Exception` classes. It will never be equal to an int nor a string... – Tomerikoo Oct 06 '21 at 08:52
  • Does this answer your question? [python exception message capturing](https://stackoverflow.com/questions/4690600/python-exception-message-capturing) – Tomerikoo Oct 06 '21 at 08:53

1 Answers1

0

This question is lacking some context and there are some conceptual mistakes here.

  1. When you use a try/except block, you're trying to catch errors that occur in your code! That can be something related to network, bad semantic or anything else, but it is something that is actually raising an Exception. So the code inside the try block is not irrevelent code, is very important that we know what you're doing.
  2. All the Exceptions that you are trying to catch are instances of a Class. Therefore, err it's an object and the comparison that you are trying doesn't make sense. The reason that can print the error is that the object has a str or repr function. For better understanding:
try:
    raise EOFError
except EOFError as e:
    print(dir(e))

This will output:

<class 'EOFError'>

  1. Reading your question it's hard to say if you're code is throwing you an error that you'll be able to catch or it's just returning you a string that the request has failed though the code runned flawlessly.
dsenese
  • 143
  • 11