Registers functions to be called if an exception or signal occurs.
ErrorHandler(func=None, *args, **kwargs)¶
Context manager for running code that must be cleaned up on failure.
The context manager allows you to register functions that will be called when an exception (excluding SystemExit) or signal is encountered. Usage:
handler = ErrorHandler(cleanup1_func, *cleanup1_args, **cleanup1_kwargs) handler.register(cleanup2_func, *cleanup2_args, **cleanup2_kwargs) with handler: do_something()
Or for one cleanup function:
with ErrorHandler(func, args, kwargs): do_something()
If an exception is raised out of do_something, the cleanup functions will be called in last in first out order. Then the exception is raised. Similarly, if a signal is encountered, the cleanup functions are called followed by the previously received signal handler.
Each registered cleanup function is called exactly once. If a registered function raises an exception, it is logged and the next function is called. Signals received while the registered functions are executing are deferred until they finish.
register(func, *args, **kwargs)¶
Sets func to be run with the given arguments during cleanup.
Parameters: func (function) – function to be called in case of an error
Calls all registered functions
Sets signal handlers for signals in _SIGNALS.
Resets signal handlers for signals in _SIGNALS.
Replacement function for handling received signals.
Store the received signal. If we are executing the code block in the body of the context manager, stop by raising signal exit.
Parameters: signum (int) – number of current signal
Finally call the deferred signals.