Find which promise failed in chain of .then - javascript

I'm trying to design a chain of promises with a catch error at the end in my node + express app. In the example below, if any one of the 'then' functions error out I'll have to work backwards to find which one from the error message. Is there an easier way to code the catch function?
new Promise(function(resolve, reject) {
resolve(groupId);
})
.then(sid => getGuestGroup2(sid))matching carts
.then(group =>getProducts(group))//add products
.then(result2 =>getPrices(result2))
.catch(error => { // (**)
console.log('Error on GET cart.js: '+error);
res.sendStatus(500);
});

The Promise chaining is generic enough to not have 'which step failed' kind of information included out of the box. You could potentially try to decode it from stack trace, but in my opinion that's way more work than its worth. Here are few options you can employ to determine which step failed.
Option 1
Set an extra property (as indicator) on the error object, which could be decoded in the catch block to determine which step in chain, the error originated from.
function predictibleErrors(promise, errorCode) {
return Promise.resolve(promise)
.catch(err => {
const newErr = new Error(err.message);
newErr.origErr = err;
newErr.errorCode = errorCode;
throw newErr;
});
}
Promise.resolve(groupId)
.then(sid => predictibleErrors(getGuestGroup2(sid), 'STEP_1')) // matching carts
.then(group => predictibleErrors(getProducts(group), 'STEP_2')) // add products
.then(result2 => predictibleErrors(getPrices(result2), 'STEP_3'))
.catch(error => { // (**)
console.log('Error on GET cart.js: '+error);
// Check error.errorCode here to know which step failed.
res.sendStatus(500);
});
Option 2
Good old, catch after every step, and re-throw to skip subsequent steps.
Promise.resolve(groupId)
.then(sid => getGuestGroup2(sid)) // matching carts
.catch(err => {
console.log('step 1 failed');
err.handled = true; // Assuming err wasn't a primitive type.
throw err;
})
.then(group => getProducts(group)) // add products
.catch(err => {
if(err.handled) { return; }
console.log('step 2 failed');
err.handled = true;
throw err;
})
.then(result2 => getPrices(result2))
.catch(err => {
if(err.handled) { return; }
console.log('step 3 failed');
err.handled = true;
throw err;
})
.catch(error => {
// Some step has failed before. We don't know about it here,
// but requisite processing for each failure could have been done
// in one of the previous catch blocks.
console.log('Error on GET cart.js: '+error);
res.sendStatus(500);
});
Please note that what we do in option two here, could also be done by the underlying methods directly. For eg. getGuestGroup2 or getProducts could include an errorCode or similar property on the error object that it throws. In this example we know step 1 or step 2 failed, but cannot know why. If the underlying methods were setting the same, they could include more accurate errorCodes with the knowledge of why the operation failed. I didn't take that route since the methods are not included in your sample and as far as I know they might not be in your control.

Related

How to Kill Surviving mutation JavaScript

I have this code
const writeToDB = async (data) => {
console.log("Inside db put")
try {
const resp = await dynamoDB.put(data).promise();
console.log("Data added db: ", resp);
return "successfully inserted"
} catch (err){
throw new Error(`Failed to write in database`, err)
}
}
I have 2 tests for this functionality one to check when its sucessful and one where it throws an error.
When I run stryker I get a surviving mutation
- } catch (err){
- throw new Error(`Failed to write in database`, err)
- }
+ } catch (err){}
I believe this is trying to find a test "if it catches the error but does not throw the error".
How do I write a test to kill this particular Blockstatement mutation. The code is always going to throw the error that I have specified.
The mutation test is entirely correct. The approach
return mm.putMetadataItem(metadata).catch(err => {
assert.throws(() => {
throw error
}, err)
})
to check for the expected behaviour of the putMetadataItem function is wrong. In particular, if the returned promise is not rejected, the .catch() callback with your assertion doesn't run at all, and the fulfilled promise is returned, which causes the unit test to pass. Also assert.throws is rather pointless here, you know for sure that throw error will throw, so all this does is to check equality between error and err.
You would need to write
return mm.putMetadataItem(metadata).then(() => {
throw new AssertionError('expected putMetadataItem() to reject');
}, err => {
assert.equal(error, new Error('Failed to write in database'));
});
however you actually should use assert.rejects:
return assert.rejects(() => {
return mm.putMetadataItem(metadata);
}, new Error('Failed to write in database'));

Firebase Functions How To Handle Errors Properly [duplicate]

This question already has an answer here:
Google Cloud Functions - warning Avoid nesting promises promise/no-nesting
(1 answer)
Closed 3 years ago.
NOTE: this question is mainly about error handling, and if this is an ok approach, not about nesting promises, please read before closing
Since there are currently no error codes for services like firestore and firebase database, i'm using a system to know where the function failed and to handle error accordingly, simplified version below:
exports.doStuff = functions.https.onCall((data, context) => {
return [promise doing stuff goes here].catch(error => { throw new Error('ERROR0') })
.then(result => {
return [promise doing stuff goes here, needs result of previous promise]
.catch(error => { throw new Error('ERROR1') })
})
.then(result => {
return [promise doing stuff goes here, needs result of previous promise]
.catch(error => { throw new Error('ERROR2') })
})
.then(result => {
//inform client function successful
return {
success: true
}
})
.catch(error => {
if (error !== null) {
switch (error.message) {
case 'ERROR0':
//do stuff
throw new functions.https.HttpsError('unknown', 'ERROR0');
case 'ERROR1':
//do stuff
throw new functions.https.HttpsError('unknown', 'ERROR1');
case 'ERROR2':
//do stuff
throw new functions.https.HttpsError('unknown', 'ERROR2');
default:
console.error('uncaught error: ', error);
throw error;
}
}
});
});
the thing is, for each .catch() inside each returned promise, i'm getting the following warning: warning Avoid nesting promises
so my question is, is there a better way to handle errors?
Ultimately it's a style recommendation to prevent bizarre and hard to recognise errors. Most of the time a rewrite can eliminate the warning. As an example, you could rewrite your code as the following whilst retaining the same functionality.
exports.doStuff = functions.https.onCall(async (data, context) => {
const result1 = await [promise doing stuff goes here]
.catch(error => {
throw new functions.https.HttpsError('unknown', 'ERROR0', { message: error.message } )
});
const result2 = await [promise based on result1 goes here]
.catch(error => {
throw new functions.https.HttpsError('unknown', 'ERROR1', { message: error.message } )
});
const result3 = await [promise based on result1/result2 goes here]
.catch(error => {
throw new functions.https.HttpsError('unknown', 'ERROR2', { message: error.message } )
});
return {
success: true
};
});
Lastly, rather than using unknown everywhere, you could use one of several possible values for the first argument whilst passing in whatever supporting information you need as the third argument (as shown above where I pass through the original error message).

how to differentiate error's source based on stage in Promise chain

I have 2 callback that both call API and return Promise. They should go sequentially. Let's name them verifyThing and updateThing.
So without error handling it would be as easy as
verifyThing()
.then((id) => updateThing(id))
But now error handling comes. Suppose I need to display different error message once verifyThing fails or updateThing. Also obviously I don't need to call updateThing if verifyThing fails.
So far I've tried with custom Error:
class VerifyError extends Error {};
verifyThing()
.catch(e => {
message("cannot verify");
throw new VerifyError();
})
.then((id) => updateThing(id))
.catch(e => {
if (e instanceof VerifyError) return;
message("cannot update");
})
Unfortunately custom Error check does not work with Babel 6.26 we use. As a dirty patch I can throw magic string instead of Error subclass, but ESLint rules are for a reason, right?
So finally I have got working variant. But I believe it has worse readability(because of nesting):
verifyThing()
.catch(e => {
message("cannot verify");
throw e;
})
.then((id) =>
updateThing(id)
.catch(e => {
message("cannot update");
})
)
Is there any other way to handle all the logic in the same chain?
It seems like the actual behavior you want can be achieved by reordering your last example:
verifyThing().then(id =>
updateThing(id).catch(e => {
message("cannot update");
})
).catch(e => {
message("cannot verify");
})
The outer catch() will only catch errors from verifyThing() since errors from updateThing(id) have been handled by the inner catch(). In addition, you're always left with a resolved promise instead of a rejected one, which is appropriate since both types of errors have been handled already.
To avoid the appearance that error handling is not close to the source, move the inner portion to a helper function:
function tryUpdateThing (id) {
return updateThing(id).catch(e => {
message("cannot update");
});
}
verifyThing().then(
tryUpdateThing
).catch(e => {
message("cannot verify");
});
Whether or not this is acceptably readable, I'll leave up to you to decide.
If async/await is an option, then:
async function() {
let id;
try {
id = await verifyThing();
await updateThing(id);
} catch(e) {
message(id === undefined ? "cannot verify" : "cannot update");
throw e;
}
}
This assumes that when verifyThing() fulfills, it will resolve with a defined value.

Breaking promise chain with thrown exception

Currently, if there is an error caught in asyncFunction1()s promise callback, the app will correctly throw the 'Problem A' exception. However, this is passed through the promise chain and the app will eventually see 'Problem B', which means the app is showing the wrong error to the user.
I effectively need to abort execution and break the chain whilst throwing the relevant error. How can I do this?
The HttpsError class information can be found here: https://firebase.google.com/docs/reference/functions/functions.https.HttpsError
It explicitly mentions:
Make sure to throw this exception at the top level of your function
and not from within a callback, as that will not necessarily terminate
the function with this exception.
I seem to have fallen into this trap, but do not know how to work around it. If someone could help me refactor the code so that I can effectively catch and handle these errors properly that would be much appreciated.
exports.charge = functions.https.onCall(data => {
asyncFunction1()
.then(() => {
asyncFunction2();
})
.catch((err) => {
throw new functions.https.HttpsError(
'not-found',
'Problem A'
);
})
.then(() => {
asyncFunction3();
})
.catch((err) => {
throw new functions.https.HttpsError(
'not-found',
'Problem B'
);
})
});
There are a number of different ways to approach this:
You can have each async function just set the appropriate error when it rejects so you don't have to manually add the right error in your own .catch().
You can test in the last .catch() to see if an appropriate error has already been set and just rethrow it if so rather than override it with another error.
You can put the last .catch() on the asyncFunction3() call directly instead of on the whole chain like this so you're targeting only a rejection from that function with that error code:
Modified code:
exports.charge = functions.https.onCall(data => {
return asyncFunction1().then(() => {
return asyncFunction2();
}).catch((err) => {
// set appropriate error for rejection in either of the first two async functions
throw new functions.https.HttpsError('not-found', 'Problem A');
}).then(() => {
return asyncFunction3().catch((err) => {
// set appropriate error for rejection in asyncFunction3
throw new functions.https.HttpsError('not-found', 'Problem B');
});
});
});
Note: I've also added several return statements to make sure promises are being linked into the chain and returns from the exported function. And, I've condensed the logic to make it easier to read.
This might also be a case for async/await (though I'm not entirely sure if functions.https.onCall() allows this or not):
exports.charge = functions.https.onCall(async (data) => {
try {
await asyncFunction1()
await asyncFunction2();
} catch(e) {
throw new functions.https.HttpsError('not-found', 'Problem A');
}
try {
await asyncFunction3();
} catch(e) {
throw new functions.https.HttpsError('not-found', 'Problem B');
}
});
Would something like this work?
exports.charge = functions.https.onCall(data => {
return Promise.resolve().then(
() => {
return asyncFunction1();
}).then(
() => {
return asyncFunction2();
}).then(
() => {
return asyncFunction3();
}).catch(
err => {
throw new functions.https.HttpsError(err);
});
}

Rethrowing error in promise catch

I found the following code in a tutorial:
promise.then(function(result){
//some code
}).catch(function(error) {
throw(error);
});
I'm a bit confused: does the catch call accomplish anything? It seems to me that it doesn't have any effect, since it simply throws the same error that was caught. I base this on how a regular try/catch works.
There is no point to a naked catch and throw as you show. It does not do anything useful except add code and slow execution. So, if you're going to .catch() and rethrow, there should be something you want to do in the .catch(), otherwise you should just remove the .catch() entirely.
The usual point for that general structure is when you want to execute something in the .catch() such as log the error or clean up some state (like close files), but you want the promise chain to continue as rejected.
promise.then(function(result){
//some code
}).catch(function(error) {
// log and rethrow
console.log(error);
throw error;
});
In a tutorial, it may be there just to show people where they can catch errors or to teach the concept of handling the error, then rethrowing it.
Some of the useful reasons for catching and rethrowing are as follows:
You want to log the error, but keep the promise chain as rejected.
You want to turn the error into some other error (often for easier error processing at the end of the chain). In this case, you would rethrow a different error.
You want to do a bunch of processing before the promise chain continues (such as close/free resources) but you want the promise chain to stay rejected.
You want a spot to place a breakpoint for the debugger at this point in the promise chain if there's a failure.
You want to handle a specific error or set of errors, but rethrow others so that they propagate back to the caller.
But, a plain catch and rethrow of the same error with no other code in the catch handler doesn't do anything useful for normal running of the code.
Both .then() and .catch() methods return Promises, and if you throw an Exception in either handler, the returned promise is rejected and the Exception will be caught in the next reject handler.
In the following code, we throw an exception in the first .catch(), which is caught in the second .catch() :
new Promise((resolve, reject) => {
console.log('Initial');
resolve();
})
.then(() => {
throw new Error('Something failed');
console.log('Do this'); // Never reached
})
.catch(() => {
console.log('Something failed');
throw new Error('Something failed again');
})
.catch((error) => {
console.log('Final error : ', error.message);
});
The second .catch() returns a Promised that is fulfilled, the .then() handler can be called :
new Promise((resolve, reject) => {
console.log('Initial');
resolve();
})
.then(() => {
throw new Error('Something failed');
console.log('Do this'); // Never reached
})
.catch(() => {
console.log('Something failed');
throw new Error('Something failed again');
})
.catch((error) => {
console.log('Final error : ', error.message);
})
.then(() => {
console.log('Show this message whatever happened before');
});
Useful reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#Chaining_after_a_catch
Hope this helps!
There is no important difference if you leave out the catch method call completely.
The only thing it adds is an extra microtask, which in practice means you'll notice the rejection of the promise later than is the case for a promise that fails without the catch clause.
The next snippet demonstrates this:
var p;
// Case 1: with catch
p = Promise.reject('my error 1')
.catch(function(error) {
throw(error);
});
p.catch( error => console.log(error) );
// Case 2: without catch
p = Promise.reject('my error 2');
p.catch( error => console.log(error) );
Note how the second rejection is reported before the first. That is about the only difference.
So it sounds like your question is, "In the promise chain, what does the .catch() method do?"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw
The throw statement "will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate."
In the promise chain, the .then() method will return some type of data chunk. This return of the chunk will complete the promise. The successful return of the data completes the promise. You can think of the .catch() method in the same way. .catch() however will handle unsuccessful data retrieves. The throw statement completes the promise. Occasionally, you will see developers use .catch((err) => {console.log(err))} which would also complete the promise chain.
You actually don't need to re throw it, just leave the Promise.catch empty otherwise it will consider as un handle the reject and then wrap the code in a try catch and it will catch the error automatically which is passing down.
try{
promise.then(function(result){
//some code
}).catch(function(error) {
//no need for re throwing or any coding. but leave this as this otherwise it will consider as un handled
});
}catch(e){
console.log(e);
//error can handle in here
}
In the promise chain, it is better to use .catch
ex in function f2: .then(...).catch(e => reject(e));
test1 - with try catch
test2 - without try or .catch
test3 - with .catch
function f1() {
return new Promise((resolve, reject) => {
throw new Error('test');
});
}
function f2() {
return new Promise((resolve, reject) => {
f1().then(value => {
console.log('f1 ok ???');
}).catch(e => reject(e));
});
}
function test1() {
console.log('test1 - with try catch - look in F12');
try {
f2().then(() => { // Uncaught (in promise) Error: test
console.log('???'); });
} catch (e) {
console.log('this error dont catched');
}
}
function test2() {
console.log('test2 - without try or .catch - look in F12');
f2(); // Uncaught (in promise) Error: test
}
function test3() {
console.log('test3 - with .catch');
f2().then(value => {
console.log('??');
}).catch(e => {
console.log(' now its ok, error ', e);
})
}
setTimeout(() => { test1();
setTimeout(() => { test2();
setTimeout(() => { test3();
}, 100);
}, 100);
}, 100);

Categories

Resources