用另一个枚举作为钥匙枚举
我正在从事一个项目从未提出例外的项目。取而代之的是,它返回一个结果对象:
Dto = TypeVar("Dto", bound=BaseModel)
class BaseError(BaseModel):
error_code: DomainErrorEnum
message: str
def raise_error(self):
raise ErrorMap[self.error_code] # Here is the big deal
class Result(BaseModel, Generic[Dto]):
error = Optional[BaseError]
data: Optional[Dto]
其中domainerrorenum
是映射代表我们域名的slugs的枚举。
我喜欢做的是errormap
类似这样的类:
class ErrorMap(DomainErrorEnum, Enum):
DomainErrorEnum.GENERIC_ERROR = GenericErrorException
DomainErrorEnum.NOT_FOUND = CartNotFoundException
DomainErrorEnum.OUT_OF_STOCK = OutOfStockException
这样做,我有2件事很好地隔离:
- 枚举(实际上我们有许多
“ domainerrorenum”
,但是我在这里假装我们只有一个可以使我的榜样易于理解)具有代表(slugs)我所有域错误的责任的 - 责任提出任何东西,它总是返回
结果[特定DTO]
如何表示这2件事的想法?
对
# On domain module:
def specific_use_case():
result_search: Result[ProductDto] = adapter.search_product()
if product_dto.is_success:
data: ProductDto = result_search.data
result_search.business_rules_method(data) # Here, on pure business rules we throw exceptions without using our map, because here we dont use these Result pattern
return entity
result_search.error.raise_error()
Im working on a project where adapters never raise Exceptions. Instead, it returns a Result object like this:
Dto = TypeVar("Dto", bound=BaseModel)
class BaseError(BaseModel):
error_code: DomainErrorEnum
message: str
def raise_error(self):
raise ErrorMap[self.error_code] # Here is the big deal
class Result(BaseModel, Generic[Dto]):
error = Optional[BaseError]
data: Optional[Dto]
Where DomainErrorEnum
is an Enum that maps slugs that represent our DomainErrors.
What I like to do is a ErrorMap
class that works like this:
class ErrorMap(DomainErrorEnum, Enum):
DomainErrorEnum.GENERIC_ERROR = GenericErrorException
DomainErrorEnum.NOT_FOUND = CartNotFoundException
DomainErrorEnum.OUT_OF_STOCK = OutOfStockException
Doing this, I have 2 things well segregated:
- An Enum (actually we have many
"DomainErrorEnum"
, but Im pretending here that we have only one to make my example easy to understand) that has the responsability to represents (slugs) all my domain errors - A class that know which Exception it should throw whatever I want to trhow it (remember, my adapters never raise anything, it always return a
Result[SpecificDto]
object
Any idea on how to represent these 2 things?
Just for clarify:
# On domain module:
def specific_use_case():
result_search: Result[ProductDto] = adapter.search_product()
if product_dto.is_success:
data: ProductDto = result_search.data
result_search.business_rules_method(data) # Here, on pure business rules we throw exceptions without using our map, because here we dont use these Result pattern
return entity
result_search.error.raise_error()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
errormap
可能应该 be 映射(字典):ErrorMap
should probably be a map (a dictionary):