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

标签 python exception boto3

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

获取 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/

相关文章:

ruby-on-rails - rescue_from::AbstractController::ActionNotFound无法正常工作

python - 测试一个将 chalice 与 moto 一起使用的 lambda?

amazon-web-services - 需要释放所有地区所有未使用boto3关联的弹性IP

python - python print() 函数中的选项 end =""无法一致工作

Python 二维数组在某处丢失数据

python - 如何根据 Pandas 中前一个元素之间的关系从同一列创建矩阵?

exception - 为什么Haskell中的()是Enum类型却没有实现succ函数

c++ - 编写一个带有我自己的异常的包装器

Django + AWS s3 可以上传文件但不能访问它们

python - 打开具有命名范围的 Excel 文件时出现 xlrd 错误