Use register_shutdown_function instead of flush on exception