Created
February 22, 2020 16:03
-
-
Save anatoly-scherbakov/b94c386b01a2ba881f8086e18a0be569 to your computer and use it in GitHub Desktop.
Use dataclass as exception to communicate between different layers of an application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dataclasses | |
@dataclasses.dataclass(frozen=True) | |
class AgeError(Exception): | |
name: str | |
age: int | |
def __str__(self): | |
return f'{self.name}, your age {self.age} is below minimum. Go play.' | |
def age_check(): | |
age = 15 | |
name = 'John' | |
if age < 18: | |
raise AgeError(name=name, age=age) | |
def main(): | |
try: | |
age_check() | |
except AgeError as err: | |
return { | |
'status': 'error', | |
'detail': dataclasses.asdict(err) | |
} | |
else: | |
return { | |
'status': 'ok' | |
} | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment