Refactor retry_on_error to reduce complexity