gpt4 book ai didi

python - 在 python 中产生特定的异常

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:33 26 4
gpt4 key购买 nike

我想针对我遇到的错误生成一个异常。

获取 AWS session 时,用户必须输入 MFA 代码:

try:
session = boto3.Session(profile_name=aws_account,region_name='us-east-1')
except ValidationError as validation_error:
print(f"A validation error has occurred: {vallidation_error}")
except Exception as e:
print(f"An exception has occurred: {e}")
set_regions(aws_account)

异常看起来像这样:

An exception has occcurred: An error occurred (ValidationError) when calling the AssumeRole operation: 2 validation errors detected: Value '2121212dsa' at 'tokenCode' failed to satisfy constraint: Member must satisfy regular expression pattern: [\d]*; Value '2121212dsa' at 'tokenCode' failed to satisfy constraint: Member must have length less than or equal to 6

为什么我的行 except ValidationError as valid_error: 不起作用?如何生成此错误特有的异常?

最佳答案

检查以下几点:

  1. 您已经安装了botocore
  2. 使用 from botocore.exceptions import ValidationError 导入将要使用的异常

代码看起来像:

import boto3
from botocore.exceptions import ValidationError

...

try:
session = boto3.Session(profile_name=aws_account,region_name='us-east-1')
except ValidationError as validation_error:
print(f"A validation error has occurred: {vallidation_error}")
except Exception as e:
print(f"An exception has occurred: {e}")
set_regions(aws_account)

PS:看来您还没有导入脚本中的异常。

关于python - 在 python 中产生特定的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59740160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com