Refactoring: create error wrapper and remove duplicated code