Thursday, October 13, 2022

[FIXED] How to redirect to an error page depending on the response code

Issue

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'});
                }

            });
    },
},

Solution

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'});
               }
           });
   }


Answered By - Cygnus_bewickii
Answer Checked By - Candace Johnson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.