Reputation: 288
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:
Upvotes: 0
Views: 1034
Reputation: 6058
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>
Upvotes: 1