Refactor handle_command_failures method.