Refactor handleError function