Refactored error function