Factor out common message handling code