Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 337
ashakshan Avatar asked Dec 17 '22 11:12

ashakshan


1 Answers

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.

like image 190
Michael Ruth Avatar answered Jan 05 '23 18:01

Michael Ruth