Improve error handling in connect.