Refactored error handling