Search code examples
javascripttry-catches6-promise

javascript promise catch in then


I have an abstraction using knex promises: Core.js

class CoreModel {
  constructor(tableName) {
  this.table = tableName;
}

add(payload, table) {
  return this.conn()(table ? table : this.table)
    .insert(payload)
    .then(id => id)
    .catch(err => getMsg(300, err))
    .finally(() => { this.conn().destroy() });
}

I am calling in a controller:

register.js

return this.Users.add(request.payload.users)
  .then(id => id)
  .catch(err => err);

why is it that in the core.js it does go to the catch as intended but the catch does not propagate to the catch but to the then in register.js am I completely missing something with promises errors?

Really scratching my head here, it's simple but can't figure it out.

Thanks in advance :D


Solution

  • You're catching it in (add), and catching works just like it does in normal functions -- if you catch it, it disappears.

    function add(a, b) {
        try {
            return a+b;
        } catch(e) {
          return something;
        }
    }
    

    when you call 'add' within a try catch block. you'll never catch anything

    If you want the error to keep going, do something like this

    .catch(err => {getMsg(300, err); throw err;})