This is a semantics question, but I'm trying to determine the correct Error to throw in the following situation.
I have a process that sometimes is performed multiple times. If the process is performed an additional time before the first time is complete, we have thread protection that raises a DatabaseError
and blocks the process from occurring a second time. Instead of returning the generic DatabaseError
, this raises a custom error that says that the original process is still incomplete.
In lieu of the custom error, is there a "by the books" PEP error that would be more appropriate? I've read through the python PEP for database exceptions and none stuck out to me.
There is no PEP Error specification for what you would like to accomplish, however, there is an idiosyncrasy that will achieve the similar—and better—effect, which allows one to retain error context while being able to add additional information.
Within the thread, continue to use a relevant error. Outside of the thread, just use a threading.excepthook
, where you can affix your error with additional context (ie: "Thread x: raised SomeException").
Example:
def custom_hook(args):
print(f'Thread {args.thread}: raised {args.exc_type} {args.exc_value}: {args.exc_traceback}')
threading.excepthook = custom_hook
thread = threading.Thread(target=foo)
thread.start()
thread.join()
...
It is encouraged to create your own custom Exceptions where necessary. What's important is that the Error effectively expresses the context of what is happening to allow for debugging more efficiently.
https://docs.python.org/3/library/threading.html#threading.excepthook