[Vuejs]-Error handling in Vue JS – errors not caught

1👍

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{
    ...
}
👤George

Leave a comment