Skip to content

Commit

Permalink
Raise custom OutOfContextError when working outside domain context
Browse files Browse the repository at this point in the history
  • Loading branch information
subhashb committed Apr 29, 2024
1 parent 22e0d5f commit 56d5a59
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
11 changes: 8 additions & 3 deletions src/protean/adapters/repository/sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
from sqlalchemy.types import CHAR, TypeDecorator

from protean.core.model import BaseModel
from protean.exceptions import ConfigurationError, ObjectNotFoundError
from protean.exceptions import (
ConfigurationError,
ObjectNotFoundError,
OutOfContextError,
)
from protean.fields import (
Auto,
Boolean,
Expand Down Expand Up @@ -101,8 +105,9 @@ def _get_identity_type():
raise ConfigurationError(
f'Unknown Identity Type {current_domain.config["IDENTITY_TYPE"]}'
)
except RuntimeError as exc:
logger.error(f"RuntimeError while identifying data type for identities: {exc}")
except OutOfContextError:
# This happens only when the module is being imported the first time.
# All further calls will have `current_domain` available.
return sa_types.String


Expand Down
4 changes: 4 additions & 0 deletions src/protean/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,7 @@ class SendError(Exception):

class ExpectedVersionError(Exception):
"""Raised on expected version conflicts in EventSourcing"""


class OutOfContextError(RuntimeError):
"""Raised when current_domain global is accessed without an active context"""
6 changes: 4 additions & 2 deletions src/protean/globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

from werkzeug.local import LocalProxy, LocalStack

from protean.exceptions import OutOfContextError

_domain_ctx_err_msg = """\
Working outside of domain context.
This typically means that you attempted to use functionality that needed
Expand All @@ -21,14 +23,14 @@
def _lookup_domain_object(name) -> Any:
top = _domain_context_stack.top
if top is None:
raise RuntimeError(_domain_ctx_err_msg)
raise OutOfContextError(_domain_ctx_err_msg)
return getattr(top, name)


def _find_domain() -> Domain:
top = _domain_context_stack.top
if top is None:
raise RuntimeError(_domain_ctx_err_msg)
raise OutOfContextError(_domain_ctx_err_msg)
return top.domain


Expand Down

0 comments on commit 56d5a59

Please sign in to comment.