Skip to content

Commit ac9f6c3

Browse files
committed
Catch RequestException and ConnectionError everywhere
1 parent ed24990 commit ac9f6c3

24 files changed

+170
-180
lines changed

cli/findings_export.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
from queue import Queue
3333
import threading
3434
from threading import Thread
35-
from requests.exceptions import HTTPError
35+
from requests import HTTPError, RequestException
3636

3737
from cli import options
3838
from sonar.util.types import ConfigSettings
@@ -294,7 +294,7 @@ def __get_component_findings(queue: Queue[tuple[object, ConfigSettings]], write_
294294
findings_list = findings.export_findings(
295295
component.endpoint, component.key, branch=params.get("branch", None), pull_request=params.get("pullRequest", None)
296296
)
297-
except HTTPError as e:
297+
except (HTTPError, ConnectionError, RequestException) as e:
298298
log.critical("%s while exporting findings of %s, skipped", util.http_error(e), str(component))
299299
findings_list = {}
300300
write_queue.put([findings_list, False])
@@ -323,7 +323,7 @@ def __get_component_findings(queue: Queue[tuple[object, ConfigSettings]], write_
323323
if (i_statuses or not status_list) and (i_resols or not resol_list) and (i_types or not type_list) and (i_sevs or not sev_list):
324324
try:
325325
findings_list = component.get_issues(filters=new_params)
326-
except HTTPError as e:
326+
except (HTTPError, ConnectionError, RequestException) as e:
327327
log.critical("%s while exporting issues of %s, skipped", util.http_error(e), str(component))
328328
findings_list = {}
329329
else:
@@ -333,8 +333,8 @@ def __get_component_findings(queue: Queue[tuple[object, ConfigSettings]], write_
333333
if (h_statuses or not status_list) and (h_resols or not resol_list) and (h_types or not type_list) and (h_sevs or not sev_list):
334334
try:
335335
findings_list.update(component.get_hotspots(filters=new_params))
336-
except HTTPError as e:
337-
log.critical("%s while exporting hotspots of object key %s, skipped", util.http_error(e), str(component))
336+
except (HTTPError, ConnectionError, RequestException) as e:
337+
log.error("%s while exporting hotspots of object key %s, skipped", util.http_error(e), str(component))
338338
else:
339339
log.debug("Status = %s, Types = %s, Resol = %s, Sev = %s", str(h_statuses), str(h_types), str(h_resols), str(h_sevs))
340340
log.info("Selected types, severities, resolutions or statuses disables issue search")
@@ -351,7 +351,7 @@ def store_findings(components_list: dict[str, object], params: ConfigSettings) -
351351
try:
352352
log.debug("Queue %s task %s put", str(my_queue), str(comp))
353353
my_queue.put((comp, params.copy()))
354-
except HTTPError as e:
354+
except (HTTPError, ConnectionError, RequestException) as e:
355355
log.critical("%s while exporting findings of %s, skipped", util.http_error(e), str(comp))
356356

357357
threads = params.get(options.NBR_THREADS, 4)

cli/loc.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
import sys
2525
import csv
2626
import datetime
27-
from requests.exceptions import HTTPError
27+
from requests import HTTPError, RequestException
2828

2929
from cli import options
3030
import sonar.logging as log
@@ -51,7 +51,7 @@ def __get_csv_row(o: object, **kwargs) -> tuple[list[str], str]:
5151
"""Returns CSV row of object"""
5252
try:
5353
loc = o.loc()
54-
except HTTPError as e:
54+
except (HTTPError, ConnectionError, RequestException) as e:
5555
log.warning("%s, LoC export of %s skipped", util.http_error(e), str(o))
5656
loc = ""
5757
arr = [o.key, loc]
@@ -113,7 +113,7 @@ def __get_object_json_data(o: object, **kwargs) -> dict[str, str]:
113113
d = {parent_type: o.concerned_object.key, "branch": o.name, "ncloc": ""}
114114
try:
115115
d["ncloc"] = o.loc()
116-
except HTTPError as e:
116+
except (HTTPError, ConnectionError, RequestException) as e:
117117
log.warning("%s, LoC export of %s skipped", util.http_error(e), str(o))
118118
if kwargs[options.WITH_NAME]:
119119
d[f"{parent_type}Name"] = o.name

cli/measures_export.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@
2929

3030
from typing import Union
3131

32-
from http import HTTPStatus
33-
from requests.exceptions import HTTPError
32+
from requests import HTTPError, RequestException
3433
from sonar.util import types
3534
from cli import options
3635
import sonar.logging as log
@@ -283,7 +282,7 @@ def __get_measures(obj: object, wanted_metrics: types.KeyList, hist: bool) -> Un
283282
data.update(__get_json_measures_history(obj, wanted_metrics))
284283
else:
285284
data.update(__get_object_measures(obj, wanted_metrics))
286-
except HTTPError as e:
285+
except (HTTPError, ConnectionError, RequestException) as e:
287286
log.error("%s, measures export skipped for %s", util.http_error(e), str(obj))
288287
return None
289288
return data

sonar/app_branches.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424

2525
import json
2626
from http import HTTPStatus
27-
from requests.exceptions import HTTPError
27+
from requests import HTTPError, RequestException
2828
from requests.utils import quote
2929

3030
import sonar.logging as log
@@ -109,7 +109,7 @@ def create(cls, app: App, name: str, project_branches: list[Branch]) -> Applicat
109109
params["projectBranch"].append(br_name)
110110
try:
111111
app.endpoint.post(APIS["create"], params=params)
112-
except HTTPError as e:
112+
except (HTTPError, ConnectionError, RequestException) as e:
113113
if e.response.status_code == HTTPStatus.BAD_REQUEST:
114114
raise exceptions.ObjectAlreadyExists(f"app.App {app.key} branch '{name}", e.response.text)
115115
log.critical("%s while creating branch '%s' of '%s'", utilities.http_error(e), name, str(app))
@@ -184,10 +184,10 @@ def update(self, name: str, project_branches: list[Branch]) -> bool:
184184
params["projectBranch"].append(br_name)
185185
try:
186186
ok = self.endpoint.post(APIS["update"], params=params).ok
187-
except HTTPError as e:
187+
except (HTTPError, ConnectionError, RequestException) as e:
188188
if e.response.status_code == HTTPStatus.NOT_FOUND:
189189
raise exceptions.ObjectNotFound(str(self), e.response.text)
190-
log.critical("%s while updating '%s'", utilities.http_error(e), str(self))
190+
log.error("%s while updating '%s'", utilities.http_error(e), str(self))
191191
raise
192192

193193
self.name = name

sonar/applications.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
from datetime import datetime
2727
from http import HTTPStatus
2828
from threading import Lock
29-
from requests.exceptions import HTTPError
29+
from requests import HTTPError, RequestException
3030

3131
import sonar.logging as log
3232
import sonar.platform as pf
@@ -90,10 +90,10 @@ def get_object(cls, endpoint: pf.Platform, key: str) -> Application:
9090
return _OBJECTS[uu]
9191
try:
9292
data = json.loads(endpoint.get(APIS["get"], params={"application": key}).text)["application"]
93-
except HTTPError as e:
93+
except (HTTPError, ConnectionError, RequestException) as e:
9494
if e.response.status_code == HTTPStatus.NOT_FOUND:
9595
raise exceptions.ObjectNotFound(key, f"Application key '{key}' not found")
96-
log.critical("%s while getting app key '%s'", util.http_error(e), key)
96+
log.error("%s while getting app key '%s'", util.http_error(e), key)
9797
raise
9898
return cls.load(endpoint, data)
9999

@@ -133,7 +133,7 @@ def create(cls, endpoint: pf.Platform, key: str, name: str) -> Application:
133133
check_supported(endpoint)
134134
try:
135135
endpoint.post(APIS["create"], params={"key": key, "name": name})
136-
except HTTPError as e:
136+
except (HTTPError, ConnectionError, RequestException) as e:
137137
if e.response.status_code == HTTPStatus.BAD_REQUEST:
138138
raise exceptions.ObjectAlreadyExists(key, e.response.text)
139139
log.critical("%s while creating app key '%s'", util.http_error(e), key)
@@ -150,11 +150,11 @@ def refresh(self) -> None:
150150
try:
151151
self.reload(json.loads(self.get("navigation/component", params={"component": self.key}).text))
152152
self.reload(json.loads(self.get(APIS["get"], params=self.search_params()).text)["application"])
153-
except HTTPError as e:
153+
except (HTTPError, ConnectionError, RequestException) as e:
154154
if e.response.status_code == HTTPStatus.NOT_FOUND:
155155
_OBJECTS.pop(self.uuid(), None)
156156
raise exceptions.ObjectNotFound(self.key, f"{str(self)} not found")
157-
log.critical("%s while refreshing %s", util.http_error(e), str(self))
157+
log.error("%s while refreshing %s", util.http_error(e), str(self))
158158
raise
159159

160160
def __str__(self) -> str:
@@ -388,12 +388,12 @@ def add_projects(self, project_list: list[str]) -> bool:
388388
try:
389389
r = self.post("applications/add_project", params={"application": self.key, "project": proj})
390390
ok = ok and r.ok
391-
except HTTPError as e:
391+
except (HTTPError, ConnectionError, RequestException) as e:
392392
if e.response.status_code == HTTPStatus.NOT_FOUND:
393393
log.warning("Project '%s' not found, can't be added to %s", proj, self)
394394
ok = False
395395
else:
396-
log.critical("%s while adding projects to %s", util.http_error(e), str(self))
396+
log.error("%s while adding projects to %s", util.http_error(e), str(self))
397397
raise
398398
return ok
399399

sonar/branches.py

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from http import HTTPStatus
2323
import json
2424
from urllib.parse import unquote
25-
from requests.exceptions import HTTPError
25+
from requests import HTTPError, RequestException
2626
import requests.utils
2727

2828
from sonar import platform
@@ -89,8 +89,8 @@ def get_object(cls, concerned_object: projects.Project, branch_name: str) -> Bra
8989
return _OBJECTS[uu]
9090
try:
9191
data = json.loads(concerned_object.endpoint.get(APIS["list"], params={"project": concerned_object.key}).text)
92-
except HTTPError as e:
93-
if e.response.status_code == HTTPStatus.NOT_FOUND:
92+
except (HTTPError, ConnectionError, RequestException) as e:
93+
if isinstance(HTTPError, e) and e.response.status_code == HTTPStatus.NOT_FOUND:
9494
raise exceptions.ObjectNotFound(concerned_object.key, f"Project '{concerned_object.key}' not found")
9595
log.critical("%s while getting branch '%s' of %s", util.http_error(e), branch_name, str(concerned_object))
9696
raise
@@ -129,11 +129,10 @@ def refresh(self) -> Branch:
129129
"""
130130
try:
131131
data = json.loads(self.get(APIS["list"], params={"project": self.concerned_object.key}).text)
132-
except HTTPError as e:
133-
if e.response.status_code == HTTPStatus.NOT_FOUND:
132+
except (HTTPError, ConnectionError, RequestException) as e:
133+
if isinstance(HTTPError, e) and e.response.status_code == HTTPStatus.NOT_FOUND:
134134
raise exceptions.ObjectNotFound(self.key, f"{str(self)} not found in SonarQube")
135-
log.critical("%s while refreshing %s", util.http_error(e), str(self))
136-
raise
135+
log.error("%s while refreshing %s", util.http_error(e), str(self))
137136
for br in data.get("branches", []):
138137
if br["name"] == self.name:
139138
self._load(br)
@@ -186,11 +185,11 @@ def delete(self) -> bool:
186185
"""
187186
try:
188187
return sq.delete_object(self, APIS["delete"], {"branch": self.name, "project": self.concerned_object.key}, _OBJECTS)
189-
except HTTPError as e:
190-
if e.response.status_code == HTTPStatus.BAD_REQUEST:
188+
except (HTTPError, ConnectionError, RequestException) as e:
189+
if isinstance(e, HTTPError) and e.response.status_code == HTTPStatus.BAD_REQUEST:
191190
log.warning("Can't delete %s, it's the main branch", str(self))
192191
else:
193-
log.critical("%s while deleting %s", util.http_error(e), str(self))
192+
log.error("%s while deleting %s", util.http_error(e), str(self))
194193
return False
195194

196195
def new_code(self) -> str:
@@ -203,8 +202,8 @@ def new_code(self) -> str:
203202
elif self._new_code is None:
204203
try:
205204
data = json.loads(self.get(api=APIS["get_new_code"], params={"project": self.concerned_object.key}).text)
206-
except HTTPError as e:
207-
if e.response.status_code == HTTPStatus.NOT_FOUND:
205+
except (HTTPError, ConnectionError, RequestException) as e:
206+
if isinstance(e, HTTPError) and e.response.status_code == HTTPStatus.NOT_FOUND:
208207
raise exceptions.ObjectNotFound(self.concerned_object.key, f"{str(self.concerned_object)} not found")
209208
log.error("%s while getting new code period of %s", util.http_error(e), str(self))
210209
raise e
@@ -266,8 +265,8 @@ def rename(self, new_name):
266265
log.info("Renaming main branch of %s from '%s' to '%s'", str(self.concerned_object), self.name, new_name)
267266
try:
268267
self.post(APIS["rename"], params={"project": self.concerned_object.key, "name": new_name})
269-
except HTTPError as e:
270-
if e.response.status_code == HTTPStatus.NOT_FOUND:
268+
except (HTTPError, ConnectionError, RequestException) as e:
269+
if isinstance(HTTPError, e) and e.response.status_code == HTTPStatus.NOT_FOUND:
271270
raise exceptions.ObjectNotFound(self.concerned_object.key, f"str{self.concerned_object} not found")
272271
log.error("%s while renaming %s", util.http_error(e), str(self))
273272
raise
@@ -365,9 +364,7 @@ def audit(self, audit_settings: types.ConfigSettings) -> list[Problem]:
365364
log.debug("Auditing %s", str(self))
366365
try:
367366
return self.__audit_last_analysis(audit_settings) + self.__audit_zero_loc() + self.__audit_never_analyzed()
368-
except HTTPError as e:
369-
if e.response.status_code == HTTPStatus.FORBIDDEN:
370-
log.error("Not enough permission to fully audit %s", str(self))
367+
except (HTTPError, RequestException, Exception) as e:
371368
log.error("%s while auditing %s, audit skipped", util.http_error(e), str(self))
372369
else:
373370
log.debug("Branch audit disabled, skipping audit of %s", str(self))

sonar/devops.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from http import HTTPStatus
2424
import json
2525

26-
from requests.exceptions import HTTPError
26+
from requests import HTTPError, RequestException
2727

2828
import sonar.logging as log
2929
from sonar.util import types
@@ -109,7 +109,7 @@ def create(cls, endpoint: platform.Platform, key: str, plt_type: str, url_or_wor
109109
elif plt_type == "bitbucketcloud":
110110
params.update({"clientSecret": _TO_BE_SET, "clientId": _TO_BE_SET, "workspace": url_or_workspace})
111111
endpoint.post(_CREATE_API_BBCLOUD, params=params)
112-
except HTTPError as e:
112+
except (HTTPError, ConnectionError, RequestException) as e:
113113
if e.response.status_code == HTTPStatus.BAD_REQUEST and endpoint.edition() in ("community", "developer"):
114114
log.warning("Can't set DevOps platform '%s', don't you have more that 1 of that type?", key)
115115
raise exceptions.UnsupportedOperation(f"Can't set DevOps platform '{key}', don't you have more that 1 of that type?")

sonar/hotspots.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
import json
2525
import re
2626
from http import HTTPStatus
27-
from requests.exceptions import HTTPError
27+
from requests import HTTPError, RequestException
2828
import requests.utils
2929

3030
import sonar.logging as log
@@ -402,13 +402,13 @@ def search(endpoint: pf.Platform, filters: types.ApiParams = None) -> dict[str,
402402
try:
403403
data = json.loads(endpoint.get(Hotspot.SEARCH_API, params=inline_filters, mute=(HTTPStatus.NOT_FOUND,)).text)
404404
nbr_hotspots = util.nbr_total_elements(data)
405-
except HTTPError as e:
405+
except (HTTPError, ConnectionError, RequestException) as e:
406406
if e.response.status_code == HTTPStatus.NOT_FOUND:
407407
log.warning("No hotspots found with search params %s", str(inline_filters))
408408
nbr_hotspots = 0
409409
return {}
410410
log.error("%s while searching hotspots", util.http_error(e))
411-
raise e
411+
break
412412
nbr_pages = util.nbr_pages(data)
413413
log.debug("Number of hotspots: %d - Page: %d/%d", nbr_hotspots, inline_filters["p"], nbr_pages)
414414
if nbr_hotspots > Hotspot.MAX_SEARCH:
@@ -495,8 +495,10 @@ def post_search_filter(hotspots_dict: dict[str, Hotspot], filters: types.ApiPara
495495
lang = rules.get_object(endpoint=finding.endpoint, key=finding.rule).language
496496
if lang not in filters["languages"]:
497497
filtered_findings.pop(key, None)
498+
# pylint: disable-next=E0606
498499
if "createdAfter" in filters and finding.creation_date < min_date:
499500
filtered_findings.pop(key, None)
501+
# pylint: disable-next=E0606
500502
if "createdBefore" in filters and finding.creation_date > max_date:
501503
filtered_findings.pop(key, None)
502504

sonar/issues.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,13 @@
2929
from queue import Queue
3030
from threading import Thread
3131
import requests.utils
32-
from requests.exceptions import HTTPError
32+
from requests import HTTPError, RequestException
3333

3434
import sonar.logging as log
3535
import sonar.platform as pf
3636
from sonar.util.types import ApiParams, ApiPayload, ObjectJsonRepr, ConfigSettings
3737

38-
from sonar import users, sqobject, findings, changelog, projects
38+
from sonar import users, sqobject, findings, changelog, projects, errcodes
3939
import sonar.utilities as util
4040

4141
API_SET_TAGS = "issues/set_tags"
@@ -732,7 +732,7 @@ def __search_thread(queue: Queue) -> None:
732732
i["pullRequest"] = page_params.get("pullRequest", None)
733733
issue_list[i["key"]] = get_object(endpoint=endpoint, key=i["key"], data=i)
734734
log.debug("Added %d issues in threaded search page %d", len(data["issues"]), page)
735-
except HTTPError as e:
735+
except (HTTPError, ConnectionError, RequestException, Exception) as e:
736736
log.error("%s while searching issues, search may be incomplete", util.http_error(e))
737737
queue.task_done()
738738

@@ -858,8 +858,8 @@ def count_by_rule(endpoint: pf.Platform, **kwargs) -> dict[str, int]:
858858
if d["val"] not in rulecount:
859859
rulecount[d["val"]] = 0
860860
rulecount[d["val"]] += d["count"]
861-
except HTTPError as e:
862-
log.warning("%s while counting issues per rule, count may be incomplete", util.http_error(e))
861+
except (HTTPError, Exception, RequestException) as e:
862+
log.error("%s while counting issues per rule, count may be incomplete", util.http_error(e))
863863
return rulecount
864864

865865

0 commit comments

Comments
 (0)