Saturday 22 April 2017

Knex (Bookshelf) transaction with semantic errors

Given I have a large transaction needing to be performed, I'd like to know exactly which part of the query failed. For example, if the second insert in a series of inserts failed, I'd like to provide a semantic error for error logging. Is there any way to achieve this sort of functionality?

Here's the example from Knex's docs and I've only been able to have the single catch block which generally catches any failure within a promise chain (if I understand correctly).

knex.transaction((trx) => {

  const books = [
    { title: 'Canterbury Tales' },
    { title: 'Moby Dick' },
    { title: 'Hamlet' }
  ];

  return trx
  .insert({ name: 'Old Books' }, 'id')
  .into('catalogues')
  .then((ids) => {
    return Promise.map(books, (book) => {
      book.catalogue_id = ids[0];
      return trx.insert(info).into('books');
    });
  });
})
.then((inserts) => {
  console.log(inserts.length + ' new books saved.');
})
.catch((error) => {
  // If we get here, that means that neither the 'Old Books' catalogues insert,
  // nor any of the books inserts will have taken place.
  console.error(error);
});



via Detuned

No comments:

Post a Comment