Refactor error handling