Flask 支持注册错误处理程序。定义错误处理程序可以自定义服务器错误日志以及向客户端返回更有意义的信息。
例子
import logging
import traceback
from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException
app = Flask(__name__)
logger = logging.getLogger()
@app.errorhandler(HTTPException)
def handle_http_exception(error):
error_dict = {
'code': error.code,
'description': error.description,
'stack_trace': traceback.format_exc()
}
log_msg = f"HTTPException {error_dict.code}, Description: {error_dict.description}, Stack trace: {error_dict.stack_trace}"
logger.log(msg=log_msg)
response = jsonify(error_dict)
response.status_code = error.code
return response