Close on connection error

Close and release connection if there is an error in the connection.