考虑使用'from'关键字显式重新引发的pylint建议。

10 浏览
0 Comments

考虑使用'from'关键字显式重新引发的pylint建议。

我有一段小的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": "无法获取流水线"}))
class GetPipelinesError(Exception):
    pass

Pylint警告我“考虑使用'from'关键字明确重新引发异常”。

我看到其他一些帖子中,他们使用了"from"并引发了一个错误。我做了以下修改:

except Exception as GetPipelinesError:
    logging.exception("GetPipelinesError: %s", json.dumps(GetPipelinesError))
    raise json.dumps({"httpStatus": 400, "message": "无法获取流水线"}) from GetPipelinesError

这样做对吗?

0
0 Comments

问题的出现原因是在使用raise语句时没有使用from关键字来明确地重新引发异常。在给出的代码示例中,raise语句后面的表达式应该是异常类或实例。

要解决这个问题,应该按照正确的语法使用raise-from来链接异常。在给出的代码示例中,应该将from关键字加在raise语句之后,然后跟上要引发的异常实例,如下所示:

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

这样就能正确地使用from关键字来链接异常,并确保异常信息能够正确地传递和显示。

0