I need to implement an atexit
Python function that would get the last error object and check for it's type. If the type of python error corresponds to PHP's E_ERROR
I should save the error's output to a file.
The PHP code I'm porting looks like so:
register_shutdown_function( "fatal_handler" );
function fatal_handler() {
$error = error_get_last();
if ($error != null && $error['type'] === E_ERROR)
echo "recordFatalError: {$error['message']}\n";
}
My code snap are as follows:
def fatal_handler():
# How to get last error object?
atexit.register(fatal_handler)
I would be glad if somebody explained me how can I get the necessary functionality with python.
I would use sys.last_value
for this:
import atexit
import sys
def fatal_handler():
try:
e = sys.last_value
except AttributeError: # no exception prior to execution of fatal_handler
return
atexit.register(fatal_handler)
You may choose to use getattr(sys, 'last_value', None)
in place of the EAFP approach above. It returns None
if sys.last_value
isn't available.
Alternatively, if there's just one function you want to run only when the interpreter shutdown is caused by an exception, you could use sys.excepthook
:
import sys
def fatal_handler(type, value, traceback):
e = value
sys.excepthook = fatal_handler
When an exception is raised and uncaught, the interpreter calls sys.excepthook with info about the exception. The default function prints out a given traceback and exception to sys.stderr. You can replace this function with a function which save this data. Later you can use this data in your atexit handler:
import atexit
import sys
class LastException:
value = None
type = None
trackback = None
@staticmethod
def excepthook(type,value,trackback):
LastException.type = type
LastException.value = value
LastException.trackback = trackback
@staticmethod
def register():
sys.excepthook = LastException.excepthook
def fatal_handler():
print('{0} {1}'.format( LastException.type, LastException.value))
LastException.register()
atexit.register(fatal_handler)
raise BaseException("I am an error")
# should print: <class 'BaseException'> I am an error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With