Search code examples
javascriptpythonvue.jsflask-restful

send error message from flask API to vue.js frontend if eval function giving error to apply calculation in database table


I have JSON file contains mathematical operations to apply it over columns in a database table, I am using the eval function to convert this operation and create a new data frame, sometimes JSON files contains column names not in the database table columns names so that it gives an error in eval function, I want to send message to the user that (your operation can not be done because you enter invalid name = "d/f")

JSON file looks like:

{"1": "a/b", "2": "b/c", "3": "c/d","4": "d*f"}

data frame extracted from the database

element_df =  pd.read_sql_query("select *from table where id =5",engine)

apply eval function

claculted_df = pd.dataframe()

   for i in calc_list
    try:
     calculated df = elemnt_df.eval(i)
    except pd.core.computation.ops.UndefinedVariableError:
     {"message":"your operation can not be done because you enter invalid name = d*f"}

then create pdf using report lab and finally send it to frontend

class reportAPI(source):

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('tested', type=inputs.boolean, default=True, required=False)
        # parser.add_argument('key',     type=str, default=None, required=False)
        
        report = ReportResult()
        report, info = report_.create(data, data['tested'])
        get_pdf = report.get_pdf()      
        filename = "output"
        response = make_response(get_pdf)
        return response
#=========================
api.add_resource(reportAPI, '/test')

I want the user to read the window alert with the created error message here in the test.vue response

this.$axios.post(this.$backendUrl + '/test', jsonData)
          .then(response => {
            console.log(response)
            this.fileData = { data: response.data }
            this.$emit('fileGenerated', this.fileData)

the current file: {"1": "a/b", "2": "b/c", "3": "c/d", "4":" d*f"}

the error pandas.core.computation.ops.UndefinedVariableError: name 'd*f' is not defined

the dataframe from oracle

a b c d
1 1 20 1
10 5 18 2
15 3 16 4
20 2 14 6
25 6 3 8

Solution

  • As others have stated, you can use a try/except to catch the error. Then, if the error is caught, you can return an object with the error instead of the data in this case.

    It's usually best practice for API calls to return both a success/fail boolean and the data itself. So, in this example, you could return the following (represented as JSON)...

    On success:

    {
       success: true,
       data: ...
    }
    

    When the error is caught:

    {
       success: false,
       data: "The error message"
    }
    

    You can use a JavaScript's built in alert() function to display an alert, or you can use something like vue-simple-alert.