Refactoring: Improved error handling