比较时,为什么 try/except 块中引发的异常不等于方法中的 HTTPError?
Why is raised Exception in a try/except block not equal to HTTPError in a method when compared?
- 目标:将 try except 块中的异常传递给方法,以根据错误类型定义向用户的自定义输出,而无需使用 requests.status_code 指定每个错误代码。
- 我的预期:
error == HTTPError
等同于 True
而不是 False
。
- 我尝试过的:从
HTTPError
到 requests.exceptions.HTTPError
的多种变体,以及只是四处搜索,在这里以及 google,但还没有遇到我在找什么。
当我遇到或引发 HTTPError
异常并将异常作为 e
传递给方法时,传递给该方法的参数不等于 HTTPError
。 (我理解 import *
不是最佳实践,但出于测试目的,它简化了事情。)
当我调试它并检查整个程序中异常的类型和相等性时,我得到以下信息:
e == HTTPError
False
error == HTTPError
False
type(error)
<class 'requests.exceptions.HTTPError'>
type(HTTPError)
<class 'type'>
代码:
from requests import *
def returnError(error : exceptions) -> dict:
""" Returns an updated dictionary with corresponding message matching the error """
if error == HTTPError:
result = {}
return result
try:
raise HTTPError
except (HTTPError) as e:
returnError(e)
这是因为 HTTPError
是一个 class 定义,但 e
实际上是 class 的一个实例。
类似的例子-
class Dog:
def __init__(self):
pass
type(Dog())
>> <class '__main__.Dog'>
type(Dog)
>> <class 'type'>
error == HTTPError
不起作用,因为您正在尝试将 class 与上述 class.
的实例进行比较
要检查 error
是否为 HTTPError
,请执行 isinstance(error, HTTPError)
.
- 目标:将 try except 块中的异常传递给方法,以根据错误类型定义向用户的自定义输出,而无需使用 requests.status_code 指定每个错误代码。
- 我的预期:
error == HTTPError
等同于True
而不是False
。 - 我尝试过的:从
HTTPError
到requests.exceptions.HTTPError
的多种变体,以及只是四处搜索,在这里以及 google,但还没有遇到我在找什么。
当我遇到或引发 HTTPError
异常并将异常作为 e
传递给方法时,传递给该方法的参数不等于 HTTPError
。 (我理解 import *
不是最佳实践,但出于测试目的,它简化了事情。)
当我调试它并检查整个程序中异常的类型和相等性时,我得到以下信息:
e == HTTPError
False
error == HTTPError
False
type(error)
<class 'requests.exceptions.HTTPError'>
type(HTTPError)
<class 'type'>
代码:
from requests import *
def returnError(error : exceptions) -> dict:
""" Returns an updated dictionary with corresponding message matching the error """
if error == HTTPError:
result = {}
return result
try:
raise HTTPError
except (HTTPError) as e:
returnError(e)
这是因为 HTTPError
是一个 class 定义,但 e
实际上是 class 的一个实例。
类似的例子-
class Dog:
def __init__(self):
pass
type(Dog())
>> <class '__main__.Dog'>
type(Dog)
>> <class 'type'>
error == HTTPError
不起作用,因为您正在尝试将 class 与上述 class.
要检查 error
是否为 HTTPError
,请执行 isinstance(error, HTTPError)
.