Improved error handling and connection closed behaviour