Refactor error function