As you can see from my code below, I'm using multiple "with" statements to download via SFTP.
I want to raise custom exceptions (or generally get a better idea what went wrong) based on where the error came from.
Usually I'd just wrap stuff in individual exceptions but I'm unsure how to do that here.
The code below doesn't work because my custom exceptions just bubble up, meaning I always get the ConnectionException.
try:
with pysftp.Connection(self.sftp_details["host"], username=self.sftp_details["user"],
private_key=env.root_dir+"/private.ppk", port=self.sftp_details["port"]) as sftp:
try:
with sftp.cd(self.sftp_details["folder"]):
try:
sftp.get(self.sftp_details["filename"],local_filename)
except Exception as e:
self.logErrorToSheet("The file could not be found on the server.")
raise FileNotFoundException(self.sftp_details)
except Exception as e:
self.logErrorToSheet("The folder could not be found.")
ServerFolderNotFoundException(self.sftp_details)
except Exception as e:
self.logErrorToSheet("A connection could not be made. (%s)" %(e))
raise ConnectionException(e, self.sftp_details)
Edit:
Okay so it sounds like I need to do something like:
try:
with pysftp.Connection(self.sftp_details["host"], username=self.sftp_details["user"],
private_key=env.root_dir+"/private.ppk", port=self.sftp_details["port"]) as sftp:
with sftp.cd(self.sftp_details["folder"]):
sftp.get(self.sftp_details["filename"],local_filename)
except Connection as e:
self.logErrorToSheet("A connection could not be made. (%s)" %(e))
raise e
except IOError as e:
self.logErrorToSheet("The file or folder could not be found on the server.")
raise e
I'm not quite sure how I'd tell the difference between a folder error (cd) and a file error but that's another question I can look into.