Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Does python-fire have some method to do unified exception handling? #142

Closed
hujianxin opened this issue Sep 29, 2018 · 4 comments
Closed
Labels

Comments

@hujianxin
Copy link

No description provided.

@kinow
Copy link
Contributor

kinow commented Mar 12, 2019

Came here looking for the same (as I knew click had it). Couldn't find anything in docs/examples, so I guess it leaves that part to the user?

@dbieber
Copy link
Member

dbieber commented Jul 26, 2019

That's correct.

If there's an error caused by the user's usage (e.g. they try to access a command that doesn't exist, or don't provide required arguments for a command), then internally Fire raises a FireError with details about that error. Fire catches its own errors though, and will raise a FireExit (a subclass of SystemExit that contains information about the error) with status code 2, indicating a user error.

If there's a Python error in the CLI, then Fire doesn't catch it; it simply surfaces to the user as a Python error. You can certainly catch errors raised by CLI (both ordinary Python errors as well as FireExits) if you want custom error handling code.

@dbieber
Copy link
Member

dbieber commented Aug 16, 2019

Here's the real answer to your question:

Yes, Fire catches fire.core.FireErrors and displays them succinctly alongside the usage information for the component at the time of the error.

So e.g. you can do something like

import fire, math
def sqrt(x):
  if x < 0:
    raise fire.core.FireError('x must be >= 0')
  return math.sqrt(x)
fire.Fire(sqrt)

Then when you use it you'll see:

> cli -2
ERROR: x must be >= 0
Usage: mathex.py X

For detailed information on this command, run:
  mathex.py --help

Sorry it's not in the docs yet!

@dbieber
Copy link
Member

dbieber commented Mar 10, 2020

Answered in previous comment; closing!

@dbieber dbieber closed this as completed Mar 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants