考虑使用“从”关键字PyLLT建议重新排序

2024-06-01 00:15:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个小的python代码,其中使用了异常处理

def handler(event):
    try:
        client = boto3.client('dynamodb')
        response = client.scan(TableName=os.environ["datapipeline_table"])
        return response
    except Exception as error:
        logging.exception("GetPipelinesError: %s",json.dumps(error))
        raise GetPipelinesError(json.dumps({"httpStatus": 400, "message": "Unable to fetch Pipelines"}))

class GetPipelinesError(Exception):
    pass

PyLIt警告使我“考虑使用‘从’关键字显式重新提升”。 我很少看到其他帖子,他们使用了from,并提出了一个错误。我做了这样的修改

except Exception as GetPipelinesError:
    logging.exception("GetPipelinesError: %s",json.dumps(GetPipelinesError))
    raise json.dumps({"httpStatus": 400, "message": "Unable to fetch Pipelines"}) from GetPipelinesError

这样做对吗


Tags: clientjsonmessageresponseloggingasexceptionerror
1条回答
网友
1楼 · 发布于 2024-06-01 00:15:43

不可以。raise-from的目的是为了chain exceptions。在您的案例中,正确的syntax是:

except Exception as error:
   raise GetPipelinesError(json.dumps(
       {"httpStatus": 400, "message": "Unable to fetch Pipelines"})) from error

raisefrom之后的表达式必须是异常类或实例

相关问题 更多 >