backport from trunk (rev #9973)

Improved error handling
Better re-connect handling
Credits to Ryan Bullock