Files
tembo/dev/notes/custom_exceptions.md
2021-11-09 22:46:45 +00:00

40 lines
956 B
Markdown

Custom exceptions
Create an `./exceptions.py`.
Define any custom exceptions. Can append `Error` to the exception name if needed, otherwise be descriptive.
E.g `MismatchedTokenError`, `ScopedPageAlreadyExists`.
(If it would raise a `SystemExit(1)` use an Error).
Can set custom attributes on the Exception:
```
class MismatchedTokenError(Exception):
def __init__(self, expected: int, given: int) -> None:
self.expected = expected
self.given = given
super().__init__()
```
Can refer to these when capturing the exception:
```
except exceptions.MismatchedTokenError as exec_info:
click.echo(exec_info.expected, exec_info.given)
# error handling
```
Alternatively you can pass arbitrary `*args` into the exceptions and capture them with `args[0]`:
```
raise exceptions.TemplateNotFoundError("some message")
```
```
except exceptions.TemplateFileNotFoundError as exec_info:
cli_message(exec_info.args[0])
```