简体   繁体   中英

Python catching exceptions and payload

I have the following Python Project

.\\Mainfunction.py

.\\Modules\\DatabaseFunction.py

.\\Modules\\DataBaseConnection.py

Now at the DataBaseConnection.py I am raising an exception :-

except pymysql.Error as ex:
  raise json.dumps('error payload')

This goes up a level to DatabaseFunction.py which is correct at this point I am not catching this error as I want it to filter to Mainfunction.py. My question is how do I catch this expcetion and payload at this level?

I have been messing around with the following most of the day which is miles off :-

try:
    x = DatabaseFunction.function(value1, value2, value3, etc)
except:
    print(x)
    pass

I am basically trying to pass up any caught errors to the highest level and handle them at them at the top.

I suggest to use a custom Exception for that scenario

class CustomError(Exception):
    def __init__(self, message, errors=None):
        super().__init__(message)
        self.errors = errors

so in your code you can implement something like:

except pymysql.Error as ex:
  raise CustomError('error payload')

And the catch:

try:
  x = DatabaseFunction.function(value1, value2, value3, etc)
except CustomError as e
  print(e.message)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM