Refactor error message handling