Moved socket error handler to earlier to make sure that no errors are missed