refactoring code to correctly log errors.