Fix race condition on error handling