refactors code to add validations and handle errors more directly.