Refactor for error handling