[Vuejs]-Show errors in vue component ( Noob question)

0๐Ÿ‘

I recommend axios to do the AJAX requests.

axios.post('url', formData)
.then( res => {/* success handler */})
.catch( err => { /* do your error handling here */})

for fetch function
you have everything in the first .then() block even if the request failed, then you have to return it to the second success handler which another .then() handler or throw it to the .catch() handler.

login (data, loginUrl) {
return new Promise((resolve, reject) => {
  fetch(loginUrl, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })
    .then(res => {
      if (res.status !== 200) {
        return res.json().then(res => { throw res })
      }
      return res.json()
    })
    .then((res) => {
      this.setLoginSession(res)
      resolve(res)
    })
    .catch((error) => {
      reject(error)
    })
})}

hope that helps

0๐Ÿ‘

SOLVED: HTML errors 4xx and 5xx are not caught by .catch(),

  addSpeler(){
           
           const formData = new FormData();
            formData.append('name',this.name);
            formData.append('pass_code',this.pass_code);
            formData.append('game_id', this.currentGame.id);
            
            if(this.exists === false){
                //add
                fetch(`api/speler`, {
                    method: 'post',
                    body:formData,
                })
                .then(res => { 
                    if (!res.ok){
                        this.spelerAdded = false;
                        this.errorMessage = "something went wrong ... " + res.status + " " + res.statusText;
                    }
                    else{
                    res.json();
                    console.log(res);
                    this.spelerAdded = true;
                    }
                })
                .catch(err => {
                    this.errorMessage = err.res.status;
                    this.spelerAdded = false;
                    console.log(err);
                });

            } 
        }, 

this script did the trick for me.

Leave a comment