refactor and refine error handling