Move unexpected error handling to its own function.