typer icon indicating copy to clipboard operation
typer copied to clipboard

[QUESTION] How do I disable typer's exception handler

Open cazador481 opened this issue 4 years ago • 5 comments

I want to be able to disable typer/Click's exception handler, and handle the exceptions myself. I see that in click you can do this by setting standalone_mode = False in the command.main() function.

cazador481 avatar Jun 26 '20 14:06 cazador481

to answer my own question after some digging it looks like you can do this....

if you normally have

import typer
app = typer.Typer()

if __name__ == '__main__':
     app()

you can instead do

import typer
app = typer.Typer()

if __name__ == '__main__':
    command = typer.main.get_command(app)
     
    try:
       result = command(standalone_mode=False)
    except:
       print(f'exception was thrown')

    sys.exit(result)

varioustoxins avatar Aug 04 '21 21:08 varioustoxins

I dug into the source code and found that typer.run is simply a wrapper for

app = typer.Typer()
app.command()(main)
app()` # <-- this app takes the standalone_mode argurment

jakob1379 avatar Dec 05 '22 07:12 jakob1379

I saw this question when I was looking at disabling the typer's exception message in case of issue, as it was too verbose. It's not really related to this question, but could be useful for others. What I needed to do was to disable the prettier_exceptions, which in my case only show_locals was the issue:

app = typer.Typer(add_completion=False, pretty_exceptions_show_locals = False)

or to remove the typer exception completely:

app = typer.Typer(add_completion=False, pretty_exceptions_enable=False)

sdargoeuves avatar Jan 17 '24 11:01 sdargoeuves

A disadvantage of setting standalone_mode=False is that exceptions from Click like click.UsageError won't be handled by Typer anymore. Since _original_except_hook is set when importing Typer, and is called by Typer when pretty_exceptions_enable=False, a (rather ugly) workaround is to set sys.excepthook before importing Typer.

thunze avatar Apr 29 '24 12:04 thunze

I actually preferd to add a handler for the throws, then I still benefit from more of typer's goodness:

            try:
                app()
            except SystemExit as ex:
                if ex.args[0] != 0:
                    raise
            # else continue, all is well

dereksz avatar Jun 06 '24 07:06 dereksz

[Maintenance note]: moving this to the discussion forum - we can continue the discussion there! 🙏

svlandeg avatar Jul 16 '24 15:07 svlandeg