Clean way to return error codes

Ben Finney ben+python at benfinney.id.au
Mon Nov 21 03:01:17 EST 2016


Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:

> I have a script that can be broken up into four subtasks. If any of those 
> subtasks fail, I wish to exit with a different exit code and error.
>
> Assume that the script is going to be run by system administrators who
> know no Python and are terrified of tracebacks, and that I'm logging
> the full traceback elsewhere (not shown).

The first improvement I'd make (and you likely already know this one,
but for the benefit of later readers):

    try:
        begin()
    except FooError as exc:
        print("failed to get cur: {message}".format(message=exc))
        raise SystemExit(17) from exc

That preserves the full traceback for anything that instruments that
program to try to debug what went wrong. It will also emit the message
from the underlying problem, for the user who only sees the program
output.


The next improvement I'd make is to use the “strategy” pattern, and come
up with some common key that determines what exit status you want. Maybe
the key is a tuple of (function, exception):

    exit_status_by_problem_key = {
            (begin, BeginError): 3,
            (get_cur, FooError): 17,
            (process, FooError): 12,
            (process, BarError): 12,
            (cleanup, BazError): 8,
            }

Or you might need to define the strategy as (message_template,
exit_status):

    exit_status_by_problem_key = {
            (begin, BeginError): ("error in begin: {message}", 3),
            (get_cur, FooError): ("failed to get cur: {message}", 17),
            (process, FooError): ("error in processing: {message}", 12),
            (process, BarError): ("error in processing: {message}", 12),
            (cleanup, BazError): ("cleanup failed: {message}", 8),
            }

-- 
 \      “God forbid that any book should be banned. The practice is as |
  `\                  indefensible as infanticide.” —Dame Rebecca West |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list