Skip to content

Commit

Permalink
Merge pull request #16 from explosion/feature/error-contextmanager
Browse files Browse the repository at this point in the history
  • Loading branch information
ines authored Feb 27, 2023
2 parents fc1bf11 + 951752b commit 8a5d061
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion radicli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from dataclasses import dataclass
from inspect import signature
from pathlib import Path
from contextlib import contextmanager
import json

from .parser import ArgumentParser, HelpFormatter
Expand Down Expand Up @@ -270,12 +271,17 @@ def run(self, args: Optional[List[str]] = None) -> None:
values = self.parse(args, cmd, subcommands)
sub = values.pop(self._subcommand_key, None)
func = subcommands[sub].func if sub else cmd.func
with self.handle_errors():
func(**values)

@contextmanager
def handle_errors(self):
# Catch specific error types (and their subclasses), and invoke
# their handler callback. Handlers can return an integer exit code,
# which will be passed to sys.exit.
errors_map = expand_error_subclasses(self.errors)
try:
func(**values)
yield
except tuple(errors_map.keys()) as e:
handler = errors_map[e.__class__]
err_code = handler(e)
Expand Down

0 comments on commit 8a5d061

Please sign in to comment.