Hiding tracebacks from end-users

Matthew Woodcraft mattheww at chiark.greenend.org.uk
Wed Oct 24 18:05:00 EDT 2007


Steven D'Aprano  <steve at REMOVE-THIS-cybersource.com.au> wrote:
> I'm writing a command-line application that is meant to be relatively 
> user friendly to non-technical users.

> Consequently, I'd like to suppress Python's tracebacks if an error does 
> occur, replacing it with a more friendly error message. I'm doing 
> something like this:

>try:
>    setup()
>    do_something_useful()
>except KeyboardInterrupt:
>    print >>sys.stderr, "User cancelled"
>    sys.exit(2)
>except Exception, e:
>    if expert_mode:
>        # experts get the full traceback with no hand-holding.
>        raise
>    else:
>        # print a more friendly error message
>        if isinstance(e, AssertionError):
>            msg = "An unexpected program state occurred"
>        elif isinstance(e, urllib2.HTTPError):
>            msg = "An Internet error occurred"
>        else:
>            # catch-all for any other exception
>            msg = "An error occurred"
>        print>>sys.stderr, msg
>        print>>sys.stderr, e
>        sys.exit(1)
>else:
>    sys.exit(0)

> Is this a good approach? Is there another way to suppress the traceback 
> and just print the error message?

There's traceback.format_exception_only().

If the exception value is a unicode object containing characters which
can't be encoded by sys.stderr's encoding, the code above will fail
(give an ugly traceback and fail to display the error message).

format_exception_only() would be less ugly, but it would still fail to
display the error message. So it's safest to check for this case
explicitly and encode with backslashreplace or similar.

In this situation I use bare except and sys.exc_info, rather than
'except Exception', because there are still libraries out there which
raise objects which aren't instances of Exception.

-M-




More information about the Python-list mailing list