Skip to content

Commit

Permalink
Extract error handling from client methods
Browse files Browse the repository at this point in the history
  • Loading branch information
jodal committed Nov 16, 2023
1 parent efb9927 commit 72ccab8
Showing 1 changed file with 20 additions and 20 deletions.
40 changes: 20 additions & 20 deletions src/brreg/enhetsregisteret/_client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Optional
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Generator, Optional

import httpx

Expand All @@ -11,6 +12,22 @@
from types import TracebackType


@contextmanager
def error_handler() -> Generator[None, Any, None]:
try:
yield
except httpx.HTTPError as exc:
response: httpx.Response | None = getattr(exc, "response", None)
raise BrregRestError(
str(exc),
method=(exc.request.method if exc.request else None),
url=(str(exc.request.url) if exc.request else None),
status_code=(response.status_code if response else None),
) from exc
except Exception as exc:
raise BrregError(exc) from exc


class Client:
_client: httpx.Client

Expand All @@ -37,16 +54,8 @@ def close(self) -> None:
self._client.close()

def get_enhet(self, organisasjonsnummer: str) -> Optional[Enhet]:
"""Get :class:`Enhet` given an organization number.
Returns :class:`None` if Enhet is gone or not found.
Returns :class:`Enhet` if Enhet is found.
Raises :class:`BrregRestError` if a REST error occurs.
Raises :class:`BrregError` if an unhandled exception occurs.
"""
res: Optional[httpx.Response] = None
try:
"""Get :class:`Enhet` given an organization number."""
with error_handler():
res = self._client.get(
f"/enheter/{organisasjonsnummer}",
headers={
Expand All @@ -57,12 +66,3 @@ def get_enhet(self, organisasjonsnummer: str) -> Optional[Enhet]:
return None
res.raise_for_status()
return Enhet.model_validate_json(res.content)
except httpx.HTTPError as exc:
raise BrregRestError(
str(exc),
method=(exc.request.method if exc.request else None),
url=(str(exc.request.url) if exc.request else None),
status_code=(res.status_code if res else None),
) from exc
except Exception as exc:
raise BrregError(exc) from exc

0 comments on commit 72ccab8

Please sign in to comment.