如何吞下python异常消息?

时间:2018-10-03 08:54:48

标签: python python-3.x

我因此有一些代码:

import { Component, OnInit, ViewChildren, OnDestroy } from '@angular/core';

// shared
import { ToasterService } from '../../shared/providers/toaster-service/toaster.service';

// ngx-bootstrap
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

// ngrx
import { ActionsSubject } from '@ngrx/store';

// rxjs
import { Subscription } from 'rxjs/Subscription';

  loading = <boolean>false;
  actionSub = new Subscription();
  errorMessage = <string>'';

constructor(
    private actionsSubj: ActionsSubject,
    private toastService: ToasterService,
    private bsModalRef: BsModalRef,
  ) {
    this.actionSub = this.actionsSubj.subscribe((data: any) => {
      // listen to action of setting tokens successfully / failed
      console.log(data);
      if (data.type === 'LOGIN_FAILED') {
        if (data.payload.error.error.data.type === 'WrongCredentialsException') {
          // hide spinner for login button
          this.loading = false;
          this.errorMessage = 'Wrong Credentials';
        else {
          this.loading = false;
          this.toastService.showError('An error happened when trying to login. Please try again later.');
        }
      } else if (data.type === 'SET_TOKEN') {
        this.bsModalRef.hide();
      }
    });
  } 

  ngOnDestroy() {
    this.actionSub.unsubscribe();
  }

问题在于,应用程序中其他位置的异常日志记录代码捕获了此异常并有帮助地将其打印出来-在这种情况下,看起来像这样:

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

关键是要打印出mysql连接字符串。如何防止它这样做?

2 个答案:

答案 0 :(得分:2)

使用语法:

raise Exception("Command failed") from None

请参见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

对比您看到的默认行为:

>>> 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

作为特定于您的用例的替代方法:请勿使用会引发异常的check_call,而应使用subprocess.run  代替:

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

subprocess.call

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

答案 1 :(得分:0)

您可以这样更改输出:

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