Refactored error check, according to comments on the issue.