From dc9a2b7ec91aa1adf7b59217106fe6ce45f2eb4c Mon Sep 17 00:00:00 2001 From: Yo Chiang Date: Mon, 20 Apr 2020 17:59:23 +0800 Subject: [PATCH] repo_pull: Handle abnormal responses urllib.error.HTTPError works as a http response object (same type that urlopen() returns). Handle the exception by reading and parsing the response body of the error. Test: ./repo_review.py --add-reviewer [invalid username] [query] Test: ./repo_review.py --add-reviewer [ambiguous username] [query] Change-Id: Ibfc261d83f2f9efd7873835f74ce8d5e980821c9 --- tools/repo_pull/gerrit.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/tools/repo_pull/gerrit.py b/tools/repo_pull/gerrit.py index eab28bd39..a4cd7dc36 100755 --- a/tools/repo_pull/gerrit.py +++ b/tools/repo_pull/gerrit.py @@ -26,6 +26,11 @@ import json import os import sys +try: + from urllib.error import HTTPError # PY3 +except ImportError: + from urllib2 import HTTPError # PY2 + try: from urllib.request import ( HTTPBasicAuthHandler, Request, build_opener) # PY3 @@ -146,16 +151,19 @@ def _make_json_post_request(url_opener, url, data, method='POST'): request = Request(url, data, headers) request.get_method = lambda: method - response_file = url_opener.open(request) + try: + response_file = url_opener.open(request) + except HTTPError as error: + response_file = error + + with response_file: res_code = response_file.getcode() # Nothing to parse if response is '204 No Content' if res_code == 204: return (res_code, None) res_json = _decode_xssi_json(response_file.read()) return (res_code, res_json) - finally: - response_file.close() def set_review(url_opener, gerrit_url, change_id, labels, message):