Skip to content

Instantly share code, notes, and snippets.

@anatoly-scherbakov
Created February 22, 2020 16:03
Show Gist options
  • Save anatoly-scherbakov/b94c386b01a2ba881f8086e18a0be569 to your computer and use it in GitHub Desktop.
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
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