refactor api error handling