Search code examples
pythonexceptionerror-handlingpylintraise

Consider explicitly re-raising using the 'from' keyword pylint suggestion


I have a small python code in which I am using exception handling.

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

pylint warning gives me " Consider explicitly re-raising using the 'from' keyword ". I saw few other posts, where they used from and raised an error. I made modifications like this

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

Is this the right way to do ?


Solution

  • No. The purpose of raise-from is to chain exceptions. The correct syntax in your case is:

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

    The expressions that follow raise and from must be exception classes or instances.