From c5848b0701f43c6b54307bd98feef035948a9303 Mon Sep 17 00:00:00 2001 From: Tyler Johnson Date: Sun, 9 Aug 2015 10:29:00 -0600 Subject: [PATCH] catch errors thrown in diff function --- index.js | 50 +++++++++++++++++++++++--------------------------- test/test.js | 10 ++++++++++ 2 files changed, 33 insertions(+), 27 deletions(-) diff --git a/index.js b/index.js index a8bf974..47890ad 100644 --- a/index.js +++ b/index.js @@ -12,36 +12,32 @@ if (typeof window !== 'undefined' && window.PouchDB) { // the diffFun tells us what delta to apply to the doc. it either returns // the doc, or false if it doesn't need to do an update after all function upsertInner(db, docId, diffFun) { - return new PouchPromise(function (fulfill, reject) { - if (typeof docId !== 'string') { - return reject(new Error('doc id is required')); - } - - db.get(docId, function (err, doc) { - if (err) { - /* istanbul ignore next */ - if (err.status !== 404) { - return reject(err); - } - doc = {}; - } + if (typeof docId !== 'string') { + return PouchPromise.reject(new Error('doc id is required')); + } - // the user might change the _rev, so save it for posterity - var docRev = doc._rev; - var newDoc = diffFun(doc); + return db.get(docId).catch(function (err) { + /* istanbul ignore next */ + if (err.status !== 404) { + throw err; + } + return {}; + }).then(function (doc) { + // the user might change the _rev, so save it for posterity + var docRev = doc._rev; + var newDoc = diffFun(doc); - if (!newDoc) { - // if the diffFun returns falsy, we short-circuit as - // an optimization - return fulfill({updated: false, rev: docRev}); - } + if (!newDoc) { + // if the diffFun returns falsy, we short-circuit as + // an optimization + return { updated: false, rev: docRev }; + } - // users aren't allowed to modify these values, - // so reset them here - newDoc._id = docId; - newDoc._rev = docRev; - fulfill(tryAndPut(db, newDoc, diffFun)); - }); + // users aren't allowed to modify these values, + // so reset them here + newDoc._id = docId; + newDoc._rev = docRev; + return tryAndPut(db, newDoc, diffFun); }); } diff --git a/test/test.js b/test/test.js index 0db85a3..a322749 100644 --- a/test/test.js +++ b/test/test.js @@ -373,5 +373,15 @@ function tests(dbName, dbType) { }); }); + it('errors thrown in diff function shouldn\'t crash the system', function () { + return db.upsert('foo', function () { + throw new Error("An upsert diff error."); + }).then(function () { + throw new Error("Finished upsert without throwing error."); + }, function (e) { + should.exist(e); + }); + }); + }); }