VueJS - Unable to catch the axios error in Vue/CLI project

落花浮王杯 提交于 2021-02-04 08:28:52

问题


Hello i am trying to display a message whenever the API has any error, here $http is axios

The code is given Below:

Case 1

...
<span class="badge" id="disconnected" v-if="noerror" >{{noerror.name}}</span>
<span class="badge" id="disconnected" v-if="error" >{{error}}</span>
...
isData: false,
error: null,
noerror: null,
...
status(id) {
          this.$http.get(`/status_init/${id}`)
            .then(response => {
              this.noerror = response.data
              this.isData = true
            })
            .catch ((e) => {this.error = 'No data'})

      }

Case 2

    ...template remains same...

    status(id) {
      const self = this
          self.$http.get(`/status_init/${id}`, {
          headers : {
          'Authorization': process.env.Authorization
        })
            .then(response => {
              self.noerror = response.data
              self.isData = true
            })
             .catch ((e) => {self.error = 'No data'})
      }

If i do it like case 1 then the routes with 200 status is working absolutely fine but here the routes with some other status is not displaying anything. Thus in case 1 it shows .then part only. And in console if routes does not give 200 status then i get:

GET https://----URL----2 401 (UNAUTHORIZED) in console

If i do it like case 2 then the routes with 200 status and the routes with some other status are displaying 'No Data'. Thus in case 2 it shows .catch part only. And in console for every routes I get:

GET https://----URL----2 422 unprocessable IN console

Case 1 is working fine for me as it is showing proper details for 200 Ok routes, but here only problem is that it does not show the .catch logic for status other than 200 and for me it throws 401 in case of error in routes rather than displaying 'No Data'

Please do help me, i want to catch and display message which ever the error code is. The error that i am getting currently in the postman:


回答1:


You should catch the error as below logic. You need to use two variables. One is to keep track of the response and another is for keeping the data.

...
isData: false,
noerror: null,
...

  status(id) {
    const self = this;
    self.$http.get(`/status_init/${id}`, {
        headers: {
          'Authorization': process.env.Authorization
        }).then(response => {
        self.noerror = response.data;
        self.isData = true;
      }).catch((e) => {
        self.noerror = 'No data';
        self.isData = false;
      })
    }
  }
<span class="badge" v-if="isData">{{noerror.name}}</span>
<span class="badge" v-if="!isData">{{noerror}}</span>


来源:https://stackoverflow.com/questions/65933419/vuejs-unable-to-catch-the-axios-error-in-vue-cli-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!