Add defensive checks for invalid connection

Add defensive checks for invalid connection