Improved error handling, especially around the listen loop code