Close the connection on response errors + few code improvements