Error handling and refactor