如何实现Flask API在Pandas eval函数运算出错时向Vue.js前端传递错误提示信息
Solution: Handle Undefined Column Errors in Pandas Eval & Show Custom Alert in Vue
Let's break this down into backend (Flask) and frontend (Vue) modifications to get your custom error handling working properly.
Backend (Flask) Modifications
First, we'll update your reportAPI class to:
- Catch the
UndefinedVariableErrorfrom Pandas - Return a structured JSON error response with your custom message
- Use an appropriate HTTP status code (like 400 Bad Request) to signal an error to the frontend
Here's the updated code:
from flask import jsonify, make_response import pandas as pd import json # For loading operations from your JSON file from pandas.core.computation.ops import UndefinedVariableError class reportAPI(source): def post(self): parser = reqparse.RequestParser() parser.add_argument('tested', type=inputs.boolean, default=True, required=False) args = parser.parse_args() # 1. Load math operations from your JSON file (adjust file path as needed) with open('operations.json', 'r') as f: operations = json.load(f) calc_list = list(operations.values()) # Extract operations like ["a/b", "b/c", ...] # 2. Fetch data from Oracle database element_df = pd.read_sql_query("select * from table where id =5", engine) # 3. Process operations with error handling calculated_df = pd.DataFrame() try: for idx, op in enumerate(calc_list): # Add each computed result as a new column col_name = f"calculation_{idx+1}" calculated_df[col_name] = element_df.eval(op) except UndefinedVariableError as e: # Extract the invalid operation from Pandas' error message invalid_op = str(e).split("'")[1] # Return custom error response with 400 status code return jsonify({ "message": f"无法执行运算,因输入了无效名称:{invalid_op}" }), 400 # 4. Proceed with PDF generation if no errors occur report = ReportResult() report, info = report_.create(data, args['tested']) get_pdf = report.get_pdf() filename = "output" # Set proper headers for PDF download response = make_response(get_pdf) response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] = f'attachment; filename={filename}.pdf' return response api.add_resource(reportAPI, '/test')
Key Backend Changes:
- Added explicit catching for
UndefinedVariableError - Parsed the invalid operation from Pandas' error message to inject into your custom prompt
- Returned a JSON error response (instead of PDF) with a 400 status code when errors occur
- Added proper headers for the PDF response to ensure frontend handles downloads correctly
Frontend (Vue) Modifications
Next, update your Axios request to handle the error response from the backend and show a popup alert to the user. You can use a native alert or a UI library component (like Element UI's MessageBox — adjust based on your frontend setup).
Here's the updated Vue code:
this.$axios.post(this.$backendUrl + '/test', jsonData) .then(response => { console.log(response) this.fileData = { data: response.data } this.$emit('fileGenerated', this.fileData) }) .catch(error => { // Check for custom error message from backend if (error.response && error.response.data && error.response.data.message) { // Show custom popup (use your preferred UI component here) alert(error.response.data.message); // Example using Element UI MessageBox: // this.$alert(error.response.data.message, '运算错误', { // confirmButtonText: '确定', // type: 'error' // }); } else { // Fallback for unexpected errors alert('生成报告时发生未知错误,请重试'); } })
Key Frontend Changes:
- Added a
.catch()block to handle HTTP errors (like the 400 status code from the backend) - Extracted and displayed the custom error message from the response
- Included a fallback alert for unexpected errors
- Provided examples for both native alert and Element UI components (adjust to match your frontend library)
How It Works:
- When Pandas encounters an undefined column in an operation (like
d*fwherefdoesn't exist), it throwsUndefinedVariableError - The backend catches this error, extracts the invalid operation, and sends a JSON error response
- The frontend catches the HTTP error, pulls the custom message, and displays it in a popup for the user
内容的提问来源于stack exchange,提问作者Mohamed Hassan
相关产品推荐
相关产品推荐

