Refactored error handling code in controllers to avoid duplication