让我总结一下:
我有一个包含两个类的模块(注意:此模块在包装中):
自定义Exception:
class MYAUTHError(Exception):
def __init__(self, *args, **kwargs):
print('--- MYAUTHError!!! ---')
和使用此异常的类(此处为示例):
try:
resp_login.raise_for_status()
except requests.exceptions.HTTPError as ex:
logging.error("ERROR!!! : user authentication failed)
raise MYAUTHError('oups')
在这个模块(文件)中,我知道这是可行的。例如,我可以编写如下代码并验证是否捕获到我的自定义异常:
try:
raise MYAUTHError('oups')
except MYAUTHError:
print("got it")
但是,当从另一个模块(导入该模块的模块)中使用时,我无法成功捕获此自定义异常...
from mypackage import mymodulewithexception
# somewhere in the code, just to test. OK : my class is known.
extest = mymodulewithexception.MYAUTHError('**-test-**')
print(type(extest))
# but this does not catch anything :
except mymodulewithexception.MYAUTHError as ex:
logging.error("Authentication failed", ex)
return
我敢肯定,抛出了异常,因为调用模块是一个Flask应用程序,并且调试服务器清楚地向我显示了异常是由于未处理而抛出的。
在试图理解这一点时,我只是用另一个著名的异常:ValueError替换了我的自定义异常。我在调用模块中更改代码以捕获此问题:当然可以。
我什至试图捕获一个Exception(真正的通用类):
except mymodulewithexception.MYAUTHError as ex:
print("got it")
except Exception as ex:
print('----------------------------------------------------')
print(ex)
print('-------------------')
我的自定义异常在第一个捕获中被忽略,但在第二个捕获中被捕获...
怎么可能是我的自定义异常未正确捕获?
也许,包上下文?
谢谢你的帮助!
参考方案
通过尝试在一个小示例中进行重现,我意识到它来自我的模块组织...编辑:这是在包装中导入模块的错误方法
让我们总结一个例子:有2个包(pack1和pack2)。
文件系统上的组织是这样的:
a_directory
|
|--pack1
| |-- __init__.py
| |-- mymodulewithexception.py
| |-- inheritclass.py
|
|--pack2
|-- __init__.py
|-- callerModule.py
pack1.mymodulewithexception.py:
class MYAUTHError(Exception):
def __init__(self, *args, **kwargs):
print('--- MYAUTHError!!! ---')
class UseMyAUTH:
def testEx(self):
print("I am going to user your custom exception!")
raise MYAUTHError('oups')
pack1.inheritclass.py:
import sys
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_path)
from mymodulewithexception import UseMyAUTH
class BlablaClass(UseMyAUTH):
pass
编辑:这种在pack1.inheritclass.py中导入模块的方法是错误的
编辑:代替:
from .mymodulewithexception import UseMyAUTH
class BlablaClass(UseMyAUTH):
pass
pack2.callerModule.py
from pack1 import mymodulewithexception, inheritclass
blabla = inheritclass.UseMyAUTH()
try:
blabla.testEx()
except mymodulewithexception.MYAUTHError:
print('Catched')
我这样运行:
d:\a_directory> python -m pack2.callerModule
抛出但没有被“拦截”的异常:
mymodulewithexception.MYAUTHError: oups
编辑:现在可以使用了!!!
Python ThreadPoolExecutor抑制异常 - pythonfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
python异常消息格式 - pythonon-topic 免责声明:我会删除这个问题,因为它是如此..总之,投票表明我并不是唯一一个表现不佳的人。所以我将其留给他人。题:为什么在使用%s格式化消息时却没有收到异常消息,但使用format却可以呢?失败:>>> Exception('foo %s', 'bar').message '…