You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS Lambda的Python自定义异常中添加errorcode字段

解决方案

AWS Lambda 默认处理未捕获异常时,只会生成包含 errorMessage、errorType 和 stackTrace 的响应,不会自动包含自定义异常类的属性。要添加 errorcode 字段,你需要手动捕获异常并构造符合要求的响应结构。

步骤1:给自定义异常类添加 errorcode 属性

首先修改你的异常类,加入自定义的 errorcode 字段:

class UserAccessibilityError(Exception):
    def __init__(self, e: Exception, msg=None, debug=None):
        if msg is None:
            msg = " User authentication failure"
        super().__init__(msg)
        self.e = e
        self.retryable = 'N'
        self.item = " User authentication failure"
        self.errorcode = "4XX"  # 新增自定义错误码字段

步骤2:在 Lambda 处理函数中捕获异常并构造响应

不要让异常直接抛出给 Lambda 自动处理,而是手动捕获自定义异常,构造包含 errorcode 的响应字典:

import traceback

def lambda_handler(event, context):
    try:
        # 这里写你的业务逻辑代码
        # ...
        # 模拟触发认证失败异常
        raise Exception("user is not authorized to assume iam role")
    except Exception as error:
        msge = str(error).lower()
        if "user" in msge and "is not authorized to assume iam role" in msge:
            custom_err = UserAccessibilityError(error)
            # 构造带errorcode的响应
            return {
                "errorMessage": custom_err.args[0],
                "errorcode": custom_err.errorcode,
                "errorType": type(custom_err).__name__,
                "stackTrace": traceback.format_exc().splitlines()  # 可选:生成真实堆栈信息
            }
        # 其他异常按Lambda默认方式处理
        raise error

可选:直接构造响应(无需抛出自定义异常)

如果不需要复用自定义异常的其他属性,也可以直接在捕获原始异常后构造响应:

def lambda_handler(event, context):
    try:
        # 业务逻辑代码
        # ...
    except Exception as error:
        msge = str(error).lower()
        if "user" in msge and "is not authorized to assume iam role" in msge:
            return {
                "errorMessage": " User authentication failure",
                "errorcode": "4XX",
                "errorType": "UserAccessibilityError",
                "stackTrace": []
            }
        # 其他异常抛出,让Lambda默认处理
        raise error

注意事项

  • 如果你的 Lambda 是通过 API Gateway 对外提供服务,需要把响应包装成 API Gateway 要求的格式(包含 statusCode 和 body):
    import json
    
    return {
        "statusCode": 403,
        "body": json.dumps({
            "errorMessage": " User authentication failure",
            "errorcode": "4XX",
            "errorType": "UserAccessibilityError",
            "stackTrace": []
        })
    }
    

内容的提问来源于stack exchange,提问作者user3624000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 07:05:08