Keith
Keith

Reputation: 1038

Error handling in Vue JS - errors not caught

I have the following code:

fooService.update(this.bar).then( this.$emit('updated', this.updatedBar),).catch(err => {...

If an error is encountered, then the error is not caught. If I change the code to be:

fooService.update(this.bar).then(x => {this.$emit('updated', this.updatedBar);}).catch(err => {...

Then the error is caught and shows as expected. Can anyone explain to me what is going on and why it behaves in that way?

Edit

Underlying service code:

function updateBar(bar) {
  return $http.put(`/api/bar/${bar.Id}`, bar);
}

Upvotes: 0

Views: 1089

Answers (1)

George
George

Reputation: 6739

So I still think the error is happening in the this.$emit the reason why, in

fooService.update(this.bar).then( this.$emit('updated', this.updatedBar),).catch(err => {

It has to evaluate the this.$emit first as you're setting the response from that function as the .then and not the call itself.

Proof of it doing that

function emit(){
  console.log('emit')
}

var promise = new Promise(function(resolve,reject){
setTimeout(() => {
  console.log('promise is done')
  reject();
}, 1000)
})

promise.then(emit()).catch( function() {console.log('carry on');})

notice how it logs "emit" first

Now if that errors you can see it doesn't hit the catch

function emit(){
  console.log('emit')
  throw new Error("bad")
}

var promise = new Promise(function(resolve,reject){
setTimeout(() => {
  console.log('promise is done')
  reject();
}, 1000)
})

promise.then(emit()).catch( function() {console.log('carry on');})

So under the hood it's doing this (the simplest way I can think of)

emit()

try{
    getService()
} catch{
    ...
}

Whereas if you actually pass the .then a function it changes the order of things

function emit(){
  console.log('emit')
  throw new Error("bad")
}

var promise = new Promise(function(resolve,reject){
setTimeout(() => {
  console.log('promise is done')
  reject();
}, 1000)
})

promise.then(() => {emit()}).catch( function() {console.log('carry on');})

and again under the hood it looks like this

try{
    getService()
    emit()
} catch{
    ...
}

Upvotes: 1

Related Questions