Refactored common error handling code to a function