考虑使用 'from' 关键字 pylint 建议明确重新加注

ash*_*han 2 python error-handling exception pylint raise

我有一个小的 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
Run Code Online (Sandbox Code Playgroud)

pylint 警告给了我“考虑使用 'from' 关键字明确重新提高”。我很少看到其他帖子,他们使用 from 并引发错误。我做了这样的修改

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

这是正确的做法吗?

Mic*_*uth 6

不。raise-的目的from链接异常。您的情况的正确语法是:

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

下面的表达式raisefrom必须是异常类或实例。