Skip to content

Commit

Permalink
refactor: extract error code to exception mapping to class variable
Browse files Browse the repository at this point in the history
  • Loading branch information
federicobond committed Mar 12, 2024
1 parent 62b6301 commit 351ec14
Showing 1 changed file with 30 additions and 29 deletions.
59 changes: 30 additions & 29 deletions openfeature/exception.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,10 @@
from __future__ import annotations

import typing
from collections.abc import Mapping
from enum import Enum


class ErrorCode(Enum):
PROVIDER_NOT_READY = "PROVIDER_NOT_READY"
PROVIDER_FATAL = "PROVIDER_FATAL"
FLAG_NOT_FOUND = "FLAG_NOT_FOUND"
PARSE_ERROR = "PARSE_ERROR"
TYPE_MISMATCH = "TYPE_MISMATCH"
TARGETING_KEY_MISSING = "TARGETING_KEY_MISSING"
INVALID_CONTEXT = "INVALID_CONTEXT"
GENERAL = "GENERAL"

@classmethod
def to_exception(
cls, error_code: ErrorCode, error_message: str
) -> OpenFeatureError:
return typing.cast(
OpenFeatureError,
{
ErrorCode.PROVIDER_NOT_READY: ProviderNotReadyError,
ErrorCode.PROVIDER_FATAL: ProviderFatalError,
ErrorCode.FLAG_NOT_FOUND: FlagNotFoundError,
ErrorCode.PARSE_ERROR: ParseError,
ErrorCode.TYPE_MISMATCH: TypeMismatchError,
ErrorCode.TARGETING_KEY_MISSING: TargetingKeyMissingError,
ErrorCode.INVALID_CONTEXT: InvalidContextError,
ErrorCode.GENERAL: GeneralError,
}.get(error_code, GeneralError)(error_message),
)


class OpenFeatureError(Exception):
"""
A generic open feature exception, this exception should not be raised. Instead
Expand Down Expand Up @@ -176,3 +148,32 @@ def __init__(self, error_message: typing.Optional[str]):
raised
"""
super().__init__(ErrorCode.INVALID_CONTEXT, error_message)


class ErrorCode(Enum):
PROVIDER_NOT_READY = "PROVIDER_NOT_READY"
PROVIDER_FATAL = "PROVIDER_FATAL"
FLAG_NOT_FOUND = "FLAG_NOT_FOUND"
PARSE_ERROR = "PARSE_ERROR"
TYPE_MISMATCH = "TYPE_MISMATCH"
TARGETING_KEY_MISSING = "TARGETING_KEY_MISSING"
INVALID_CONTEXT = "INVALID_CONTEXT"
GENERAL = "GENERAL"

__exceptions__: Mapping[str, typing.Callable[[str], OpenFeatureError]] = {
PROVIDER_NOT_READY: ProviderNotReadyError,
PROVIDER_FATAL: ProviderFatalError,
FLAG_NOT_FOUND: FlagNotFoundError,
PARSE_ERROR: ParseError,
TYPE_MISMATCH: TypeMismatchError,
TARGETING_KEY_MISSING: TargetingKeyMissingError,
INVALID_CONTEXT: InvalidContextError,
GENERAL: GeneralError,
}

@classmethod
def to_exception(
cls, error_code: ErrorCode, error_message: str
) -> OpenFeatureError:
exc = cls.__exceptions__.get(error_code.value, GeneralError)
return exc(error_message)

0 comments on commit 351ec14

Please sign in to comment.