简体   繁体   English

我不知道如何处理不同的错误

[英]I can't figure out how to handle different errors

I have some code that is generating the following response:我有一些生成以下响应的代码:

The request failed: Google returned a response with code 429.请求失败:Google 返回了代码为 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.即使我正在打印 err 变量,我也无法触发这些 if 语句中的任何一个,所以我确切地知道它说的是什么。 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--->

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.当您使用 try/except 块时,您正在尝试捕获代码中出现的错误,这些错误可能与网络、错误语义或其他任何相关。 but it is something that is actually raising an Exception, So the code inside the try block is not irrevelent code.但它实际上引发了异常,因此 try 块中的代码不是无关紧要的代码。 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.您尝试捕获的所有异常都是 Class 的实例。因此,错误的是它是 object,您尝试的比较没有意义。 The reason that can print the error is that the object has a str or repr function. For better understanding:可以打印错误的原因是 object 有一个strrepr function。为了更好地理解:
try:
    raise EOFError
except EOFError as e:
    print(dir(e))

This will output:这将是 output:

<class 'EOFError'> <类'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.阅读你的问题很难说你的代码是否会抛出一个你能够捕获的错误,或者它只是返回一个字符串,表示请求失败,尽管代码运行完美。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM