user31415629
user31415629

Reputation: 1005

How can I swallow python exception messages?

I have some code thus:

try:
    subprocess.check_call(
        "mysqldump {} {}".format(mysql_args, cmd), shell=True
    )
except Exception as e:
    raise Exception("Command failed")

The problem is that Exception logging code elsewhere in the application catches this exception and helpfully prints it out - which in this case looks like this:

Traceback (most recent call last):
  File "/apps/django/myapp/tasks.py", line 336, in _safe_mysqldump
    "mysqldump {} {}".format(mysql_args, cmd), shell=True
  File "/usr/lib/python3.6/subprocess.py", line 291, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: 
Command 'mysqldump -ufoo -pMYSECRETPASSWORD myappdb t1 t2 t3...' returned non-zero exit status 6.

During handling of the above exception, another exception occurred:

etc.

The critical thing being it printed out the mysql connection string. How can I prevent it from doing this?

Upvotes: 1

Views: 1474

Answers (2)

Giacomo Alzetta
Giacomo Alzetta

Reputation: 2479

Use the syntax:

raise Exception("Command failed") from None

See PEP 409 Suppressing exception context):

>>> try:
...     raise TypeError('a')
... except TypeError:
...     raise ValueError('b') from None
... 
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError: b

Versus the default behaviour which you saw:

>>> try:
...     raise TypeError('a')
... except TypeError:
...     raise ValueError('b')
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: a

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError: b

As an alternative specific to your use case: do not use check_call which raises an exception but use subprocess.run instead:

if subprocess.run(<command>).returncode != 0:
    raise Exception("Command failed")

or subprocess.call

if subprocess.call(<command>) != 0:
    raise Exception("Command failed")

Upvotes: 3

user10325516
user10325516

Reputation:

You may change the output like this:

failed = False
try:
    ...
except Exception:
    failed = True
finally:
    if failed:
        raise Exception("Command failed")

Upvotes: 0

Related Questions