Home > Back-end >  How to redirect to an error page depending on the response code
How to redirect to an error page depending on the response code

Time:08-04

I have an api that I use to check the weather, but it may return different codes depending on the situation. In my axios.get in the catch block I want to redirect the user to an error page depending on the code returned by the server. How can this be done? I tried code below but it works wrong. When an error occurs, first the 'cityDoesntExist' page appears and then almost immediately the 'serverDoesntWork' page

methods: {
    async getWeather() {
        const cityName = this.$route.params.cityName;
        await axios.get(`/api/weather`, {params: { cityName: cityName }})
            .then(response => response.data)
            .then(data => this.weather = data)
            .catch(function (error) {
                if(error.response.status === 404) {
                    router.push({name: 'cityDoesntExist'});
                }
                if(error.response.status === 500) {
                    router.push({name: 'serverDoesntWork'});
                }

            });
    },
},

CodePudding user response:

The error could also be caused due to some other issue, which is why I would suggest you first confirm that there was response received, after which you could check what was the status in response and then use return keyword like so:

.catch(function (error) {
    if (error.response) {
      // Request made and server responded
      if(error.response.status === 404) {
          router.push({name: 'cityDoesntExist'});
          return;
      }
      if(error.response.status === 500) {
          router.push({name: 'serverDoesntWork'});
          return;
      }
    } else if (error.request) {
      // The request was made but no response was received
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }

Code referred from : Axios handling errors

CodePudding user response:

Finally, after 4 hours i found solution and it was easier, than i thought. Thanks everybody who tried to help me! Here is my solution:

async getWeather() {
       const cityName = this.$route.params.cityName;
       await axios.get('/api/weather', {params: {cityName},})
           .then(response => response.data)
           .then(data => this.weather = data)
           .catch(function (err) {
               let errJSON = err.toJSON();
               console.log(errJSON);
               if (errJSON.status === 404) {
                   return router.push({name: 'cityDoesntExist'});
               } else if (errJSON.status === 500) {
                   return router.push({name: 'serverDoesntWork'});
               }
           });
   }
  • Related