Skip to content

Commit c59ed11

Browse files
committed
More centralized exception handling
1 parent e4b08c3 commit c59ed11

23 files changed

+107
-231
lines changed

cli/projects_cli.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
2525
"""
2626

27-
import sys
2827
import json
2928

3029
from requests import RequestException

sonar/app_branches.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@
2424
from typing import Optional
2525

2626
import json
27-
from http import HTTPStatus
28-
from requests import RequestException
2927
from requests.utils import quote
3028

3129
import sonar.logging as log
@@ -112,11 +110,7 @@ def create(cls, app: object, name: str, project_branches: list[Branch]) -> Appli
112110
else: # Default main branch of project
113111
params["project"].append(obj.key)
114112
params["projectBranch"].append("")
115-
try:
116-
app.endpoint.post(ApplicationBranch.API[c.CREATE], params=params)
117-
except (ConnectionError, RequestException) as e:
118-
utilities.handle_error(e, f"creating branch {name} of {str(app)}", catch_http_statuses=(HTTPStatus.BAD_REQUEST,))
119-
raise exceptions.ObjectAlreadyExists(f"{str(app)} branch '{name}", e.response.text)
113+
app.endpoint.post(ApplicationBranch.API[c.CREATE], params=params)
120114
return ApplicationBranch(app=app, name=name, project_branches=project_branches)
121115

122116
@classmethod

sonar/applications.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,11 +128,7 @@ def create(cls, endpoint: pf.Platform, key: str, name: str) -> Application:
128128
:rtype: Application
129129
"""
130130
check_supported(endpoint)
131-
try:
132-
endpoint.post(Application.API["CREATE"], params={"key": key, "name": name})
133-
except (ConnectionError, RequestException) as e:
134-
util.handle_error(e, f"creating application {key}", catch_http_statuses=(HTTPStatus.BAD_REQUEST,))
135-
raise exceptions.ObjectAlreadyExists(key, e.response.text)
131+
endpoint.post(Application.API["CREATE"], params={"key": key, "name": name})
136132
log.info("Creating object")
137133
return Application(endpoint=endpoint, key=key, name=name)
138134

sonar/branches.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
import json
2727
import re
2828
from urllib.parse import unquote
29-
from requests import HTTPError, RequestException
3029
import requests.utils
3130

3231
from sonar import platform
@@ -173,9 +172,8 @@ def delete(self) -> bool:
173172
"""
174173
try:
175174
return super().delete()
176-
except (ConnectionError, RequestException) as e:
177-
if isinstance(e, HTTPError) and e.response.status_code == HTTPStatus.BAD_REQUEST:
178-
log.warning("Can't delete %s, it's the main branch", str(self))
175+
except exceptions.SonarException as e:
176+
log.warning(e.message)
179177
return False
180178

181179
def get(self, api: str, params: types.ApiParams = None, data: str = None, mute: tuple[HTTPStatus] = (), **kwargs) -> requests.Response:

sonar/devops.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,8 @@
2222

2323
from __future__ import annotations
2424
from typing import Optional, Union
25-
from http import HTTPStatus
2625
import json
2726

28-
from requests import RequestException
29-
3027
import sonar.logging as log
3128
from sonar.util import types, cache
3229
from sonar import platform
@@ -109,11 +106,10 @@ def create(cls, endpoint: platform.Platform, key: str, plt_type: str, url_or_wor
109106
elif plt_type == "bitbucketcloud":
110107
params.update({"clientSecret": _TO_BE_SET, "clientId": _TO_BE_SET, "workspace": url_or_workspace})
111108
endpoint.post(_CREATE_API_BBCLOUD, params=params)
112-
except (ConnectionError, RequestException) as e:
113-
util.handle_error(e, f"creating devops platform {key}/{plt_type}/{url_or_workspace}", catch_http_statuses=(HTTPStatus.BAD_REQUEST,))
109+
except exceptions.SonarException as e:
114110
if endpoint.edition() in (c.CE, c.DE):
115111
log.warning("Can't set DevOps platform '%s', don't you have more that 1 of that type?", key)
116-
raise exceptions.UnsupportedOperation(f"Can't set DevOps platform '{key}', don't you have more that 1 of that type?")
112+
raise exceptions.UnsupportedOperation(e.message) from e
117113
o = DevopsPlatform(endpoint=endpoint, key=key, platform_type=plt_type)
118114
o.refresh()
119115
return o
@@ -185,8 +181,7 @@ def update(self, **kwargs) -> bool:
185181
ok = self.post(f"alm_settings/update_{alm_type}", params=params).ok
186182
self.url = kwargs["url"]
187183
self._specific = {k: v for k, v in params.items() if k not in ("key", "url")}
188-
except (ConnectionError, RequestException) as e:
189-
util.handle_error(e, f"updating devops platform {self.key}/{alm_type}", catch_http_statuses=(HTTPStatus.BAD_REQUEST,))
184+
except exceptions.SonarException:
190185
ok = False
191186
return ok
192187

sonar/findings.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@
2424
from datetime import datetime
2525
from typing import Optional
2626
import re
27-
from http import HTTPStatus
28-
from requests import RequestException
2927
import Levenshtein
3028

3129
import sonar.logging as log
@@ -460,13 +458,10 @@ def search_siblings(
460458
def do_transition(self, transition: str) -> bool:
461459
try:
462460
return self.post("issues/do_transition", {"issue": self.key, "transition": transition}).ok
463-
except (ConnectionError, RequestException) as e:
464-
util.handle_error(e, f"applying transition {transition}", catch_http_statuses=(HTTPStatus.BAD_REQUEST, HTTPStatus.NOT_FOUND))
465461
except exceptions.SonarException as e:
466462
if re.match(r"Transition from state [A-Za-z]+ does not exist", e.message):
467463
raise exceptions.UnsupportedOperation(e.message) from e
468464
raise
469-
return False
470465

471466
def get_branch_and_pr(self, data: types.ApiPayload) -> tuple[Optional[str], Optional[str]]:
472467
"""

sonar/groups.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,6 @@
2626

2727
from typing import Optional
2828

29-
from http import HTTPStatus
30-
from requests import RequestException
31-
3229
import sonar.logging as log
3330
import sonar.platform as pf
3431
import sonar.sqobject as sq
@@ -115,11 +112,7 @@ def create(cls, endpoint: pf.Platform, name: str, description: str = None) -> Gr
115112
:return: The group object
116113
"""
117114
log.debug("Creating group '%s'", name)
118-
try:
119-
data = json.loads(endpoint.post(Group.api_for(c.CREATE, endpoint), params={"name": name, "description": description}).text)
120-
except (ConnectionError, RequestException) as e:
121-
util.handle_error(e, f"creating group '{name}'", catch_http_statuses=(HTTPStatus.BAD_REQUEST,))
122-
raise exceptions.ObjectAlreadyExists(name, util.sonar_error(e.response))
115+
data = json.loads(endpoint.post(Group.api_for(c.CREATE, endpoint), params={"name": name, "description": description}).text)
123116
o = cls.read(endpoint=endpoint, name=name)
124117
o.sq_json.update(data)
125118
return o

sonar/hotspots.py

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
from datetime import datetime
2626
from typing import Optional
2727
from http import HTTPStatus
28-
from requests import RequestException
2928
import requests.utils
3029

3130
import sonar.logging as log
@@ -36,6 +35,7 @@
3635

3736
from sonar import users
3837
from sonar import findings, rules, changelog
38+
from sonar import exceptions
3939

4040
PROJECT_FILTER = "project"
4141
PROJECT_FILTER_OLD = "projectKey"
@@ -152,19 +152,17 @@ def refresh(self) -> bool:
152152
self.rule = d["rule"]["key"]
153153
self.assignee = d.get("assignee", None)
154154
return resp.ok
155-
except (ConnectionError, RequestException) as e:
156-
util.handle_error(e, "refreshing hotspot", catch_all=True)
155+
except exceptions.SonarException:
157156
return False
158157

159158
def __mark_as(self, resolution: Optional[str], comment: Optional[str] = None, status: str = "REVIEWED") -> bool:
160159
try:
161160
params = util.remove_nones({"hotspot": self.key, "status": status, "resolution": resolution, "commemt": comment})
162-
r = self.post("hotspots/change_status", params=params)
163-
except (ConnectionError, requests.RequestException) as e:
164-
util.handle_error(e, f"marking hotspot as {status}/{resolution}", catch_all=True)
161+
ok = self.post("hotspots/change_status", params=params).ok
162+
self.refresh()
163+
return ok
164+
except exceptions.SonarException:
165165
return False
166-
self.refresh()
167-
return r.ok
168166

169167
def mark_as_safe(self) -> bool:
170168
"""Marks a hotspot as safe
@@ -215,8 +213,7 @@ def add_comment(self, comment: str) -> bool:
215213
"""
216214
try:
217215
return self.post("hotspots/add_comment", params={"hotspot": self.key, "comment": comment}).ok
218-
except (ConnectionError, requests.RequestException) as e:
219-
util.handle_error(e, "adding comment to hotspot", catch_all=True)
216+
except exceptions.SonarException:
220217
return False
221218

222219
def assign(self, assignee: Optional[str], comment: Optional[str] = None) -> bool:
@@ -231,13 +228,12 @@ def assign(self, assignee: Optional[str], comment: Optional[str] = None) -> bool
231228
log.debug("Unassigning %s", str(self))
232229
else:
233230
log.debug("Assigning %s to '%s'", str(self), str(assignee))
234-
r = self.post("hotspots/assign", util.remove_nones({"hotspot": self.key, "assignee": assignee, "comment": comment}))
235-
if r.ok:
231+
ok = self.post("hotspots/assign", util.remove_nones({"hotspot": self.key, "assignee": assignee, "comment": comment})).ok
232+
if ok:
236233
self.assignee = assignee
237-
except (ConnectionError, requests.RequestException) as e:
238-
util.handle_error(e, "assigning/unassigning hotspot", catch_all=True)
234+
return ok
235+
except exceptions.SonarException:
239236
return False
240-
return r.ok
241237

242238
def unassign(self, comment: Optional[str] = None) -> bool:
243239
"""Unassigns a hotspot (and optionally comment)
@@ -421,8 +417,7 @@ def search(endpoint: pf.Platform, filters: types.ApiParams = None) -> dict[str,
421417
try:
422418
data = json.loads(endpoint.get(Hotspot.API[c.SEARCH], params=inline_filters, mute=(HTTPStatus.NOT_FOUND,)).text)
423419
nbr_hotspots = util.nbr_total_elements(data)
424-
except (ConnectionError, RequestException) as e:
425-
util.handle_error(e, "searching hotspots", catch_all=True)
420+
except exceptions.SonarException:
426421
nbr_hotspots = 0
427422
return {}
428423
nbr_pages = util.nbr_pages(data)

sonar/issues.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -293,11 +293,9 @@ def add_comment(self, comment: str) -> bool:
293293
"""
294294
log.debug("Adding comment '%s' to %s", comment, str(self))
295295
try:
296-
r = self.post("issues/add_comment", {"issue": self.key, "text": comment})
297-
except requests.RequestException as e:
298-
util.handle_error(e, "adding comment", catch_all=True)
296+
return self.post("issues/add_comment", {"issue": self.key, "text": comment}).ok
297+
except exceptions.SonarException:
299298
return False
300-
return r.ok
301299

302300
def __set_severity(self, **params) -> bool:
303301
log.debug("Changing severity of %s from '%s' to '%s'", str(self), self.severity, str(params))
@@ -343,13 +341,11 @@ def assign(self, assignee: Optional[str] = None) -> bool:
343341
try:
344342
params = util.remove_nones({"issue": self.key, "assignee": assignee})
345343
log.debug("Assigning %s to '%s'", str(self), str(assignee))
346-
r = self.post("issues/assign", params)
347-
if r.ok:
344+
if ok := self.post("issues/assign", params).ok:
348345
self.assignee = assignee
349-
except (ConnectionError, requests.RequestException) as e:
350-
util.handle_error(e, "assigning issue", catch_all=True)
346+
return ok
347+
except exceptions.SonarException:
351348
return False
352-
return r.ok
353349

354350
def get_tags(self, **kwargs) -> list[str]:
355351
"""Returns issues tags"""
@@ -395,13 +391,11 @@ def set_type(self, new_type: str) -> bool:
395391
raise exceptions.UnsupportedOperation("Changing issue type is not supported in MQR mode")
396392
log.debug("Changing type of issue %s from %s to %s", self.key, self.type, new_type)
397393
try:
398-
r = self.post("issues/set_type", {"issue": self.key, "type": new_type})
399-
if r.ok:
394+
if ok := self.post("issues/set_type", {"issue": self.key, "type": new_type}).ok:
400395
self.type = new_type
401-
except (ConnectionError, requests.RequestException) as e:
402-
util.handle_error(e, "setting issue type", catch_all=True)
396+
return ok
397+
except exceptions.SonarException:
403398
return False
404-
return r.ok
405399

406400
def is_wont_fix(self) -> bool:
407401
"""

sonar/permissions/permission_templates.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,10 @@
2424

2525
import json
2626
import re
27-
from requests import RequestException
2827

2928
import sonar.logging as log
3029
from sonar.util import types, cache
31-
from sonar import sqobject, utilities
30+
from sonar import sqobject, utilities, exceptions
3231
from sonar.permissions import template_permissions
3332
import sonar.platform as pf
3433
from sonar.audit.rules import get_rule, RuleId
@@ -136,7 +135,7 @@ def permissions(self) -> template_permissions.TemplatePermissions:
136135
self._permissions = template_permissions.TemplatePermissions(self)
137136
return self._permissions
138137

139-
def set_as_default(self, what_list: list[str]) -> None:
138+
def set_as_default(self, what_list: list[str]) -> bool:
140139
"""Sets a permission template as default for projects or apps or portfolios"""
141140
log.debug("Setting %s as default for %s", str(self), str(what_list))
142141
ed = self.endpoint.edition()
@@ -146,9 +145,9 @@ def set_as_default(self, what_list: list[str]) -> None:
146145
log.warning("Can't set permission template as default for %s on a %s edition", qual, ed)
147146
continue
148147
try:
149-
self.post("permissions/set_default_template", params={"templateId": self.key, "qualifier": qual})
150-
except (ConnectionError, RequestException) as e:
151-
utilities.handle_error(e, f"setting {str(self)} as default")
148+
return self.post("permissions/set_default_template", params={"templateId": self.key, "qualifier": qual}).ok
149+
except exceptions.SonarException:
150+
return False
152151

153152
def set_pattern(self, pattern: str) -> PermissionTemplate:
154153
"""Sets a permission template pattern"""

0 commit comments

Comments
 (0)