从 Google Colaboratory 机密中的 userdata.get() 捕获 MessageError 异常

问题描述 投票:0回答:1

我正在尝试使用Google Colab中的userdata.get()函数来检索秘密,并且我想处理秘密不存在的情况。这是我的代码:

from google.colab import userdata
try:
  userdata.get('mySecret')
except MessageError:
  print("The mySecret doesn't exists")

但是我得到了这个名称错误:

---------------------------------------------------------------------------

MessageError                              Traceback (most recent call last)

<ipython-input-7-32b2ab9e6be3> in <cell line: 2>()
      2 try:
----> 3   userdata.get('mySecret')
      4 except MessageError:

3 frames

MessageError: Error: Secret mySecret does not exist.


During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)

<ipython-input-7-32b2ab9e6be3> in <cell line: 2>()
      2 try:
      3   userdata.get('mySecret')
----> 4 except MessageError:
      5   print("The mySecret doesn't exists")

NameError: name 'MessageError' is not defined

但是,我遇到了 NameError 而不是捕获 MessageError。错误消息表明该秘密不存在,但我无法正确处理它。

有人可以帮我理解我做错了什么吗?当找不到秘密时,如何捕获 MessageError 并打印所需的消息?

我希望它捕获了它将打印的错误:

The mySecret doesn't exists
python google-colaboratory
1个回答
0
投票

您的解决方案非常接近。看来您发现了错误的错误。

您应该抓住

MessageError
,而不是抓住
SecretNotFoundError

from google.colab import userdata
try:
  userdata.get('mySecret')
except userdata.SecretNotFoundError:
  print("The mySecret doesn't exists")

这将按预期打印。

The mySecret doesn't exists
© www.soinside.com 2019 - 2024. All rights reserved.