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
This commit is contained in:
Yo Chiang
2020-04-20 17:59:23 +08:00
parent c8827d1fd8
commit dc9a2b7ec9

View File

@@ -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):