def add_error_handler(app): for exception in default_exceptions: app.register_error_handler(exception, error_handler) app.register_error_handler(Exception, error_handler) def error_handler(error): description = error.get_description(request.environ) if hasattr(error, ‘get_description‘) else None exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) current_app.logger.error( """ Request: {method} {path} IP: {ip} User: {user} Agent: {agent_platform} | {agent_browser} {agent_browser_version} Raw Agent: {agent} Description: {description} """.format( method=request.method, path=request.path, ip=request.remote_addr, agent_platform=request.user_agent.platform, agent_browser=request.user_agent.browser, agent_browser_version=request.user_agent.version, agent=request.user_agent.string, user=g.user if hasattr(g, ‘user‘) else None, description=description, ), exc_info=exc_traceback ) if isinstance(error, HTTPException): code = error.code if code == 404: return make_response(jsonify({‘code‘: 404, ‘data‘: {}, ‘msg‘: ‘page not found‘}), code) else: """其他HTTP异常处理暂未定义""" pass else: current_app.logger.error(‘Internal Server Error‘) return make_response(jsonify({‘code‘: 500, ‘data‘: {}, ‘msg‘: ‘Internal Server Error‘}))
app = Flask(__name__) add_error_handler(app)
时间: 2024-11-13 18:14:48