自定义AWS Lambda异常类抛出TypeError:异常需继承BaseException
问题原因与解决办法
你碰到的TypeError: exceptions must derive from BaseException错误,本质是你的HTTPException类虽然继承了Exception,但重写的__new__方法没有返回该类的实例,而是直接返回了一个字典。Python对抛出的异常有严格要求:必须是BaseException(或其子类)的实例,而你现在生成的是字典对象,不符合异常类型的规范,所以触发了错误。
修正方案1:让类成为合法的异常类
如果你确实需要把它作为异常抛出并处理,应该保留异常实例的特性,同时提供转换为Lambda响应格式的方法。修改后的代码如下:
class HTTPException(Exception): def __init__(self, error_code, error_message): super().__init__(error_message) self.error_code = error_code self.error_message = error_message def to_lambda_response(self): return { "statusCode": self.error_code, "body": self.error_message, "headers": {"Access-Control-Allow-Origin": "*"}, } @classmethod def magic_func(cls, err): return cls( error_code=err.Code, error_message=err.Message, )
使用示例:
try: # 业务逻辑代码,触发异常时抛出 raise HTTPException(400, "参数格式错误") except HTTPException as e: return e.to_lambda_response()
修正方案2:改为普通工具类(无需继承Exception)
如果你的核心需求只是生成Lambda的错误响应格式,不需要抛出异常,那完全没必要让类继承Exception,直接做成普通工具类更合理:
class HTTPResponse: @classmethod def magic_func(cls, err): return { "statusCode": err.Code, "body": err.Message, "headers": {"Access-Control-Allow-Origin": "*"}, } @classmethod def from_code_message(cls, error_code, error_message): return { "statusCode": error_code, "body": error_message, "headers": {"Access-Control-Allow-Origin": "*"}, }
使用示例:
# 直接生成并返回响应 return HTTPResponse.magic_func(your_error_object)
内容的提问来源于stack exchange,提问作者Bratty Neal
相关产品推荐
相关产品推荐

