python traceback捕获并打印异常

1、traceback.print_exc()
2、traceback.format_exc()
3、traceback.print_exception()

简单说下这三个方法是做什么用的:
1、print_exc():是对异常栈输出
2、format_exc():是把异常栈以字符串的形式返回,print(traceback.format_exc()) 就相当于traceback.print_exc()
3、print_exception():traceback.print_exc()实现方式就是traceback.print_exception(sys.exc_info()),可以点sys.exc_info()进去看看实现

import json
import traceback
from  context import InteropHandler
from flask import Flask, request, json, jsonify, Response


dialog = Flask(__name__)


@dialog.route('/d', methods=['POST'])
def interop():
    if request.method == 'POST':
        try:
            json_data = request.get_data()
            d_content = InteropHandler.interop(json_data)
            return Response(json.dumps(d_content), status=200, mimetype='application/json')
        except Exception:
            #构建错误内容...
            erro = {'code':100, 'msg': traceback.format_exc()}
            return Response(json.dumps(erro), status=500,mimetype='application/json')
        finally:
            pass
    return Response('请求方法不支持的{}'.format(request.method), status=400)

上一篇:python打印表格式数据-星号或注释


下一篇:python库——sys模块