factored out shared error handling code