我想针对我遇到的错误生成一个异常。
获取 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:
不起作用?如何生成此错误特有的异常?
最佳答案
检查以下几点:
- 您已经安装了
botocore
库 - 使用
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/