refactored error handling