I'm wrapping my head around the new ecma6 generators and yield-operator in javascript, specifically in the context of koa.
Consider the contrived example:
newUser.save(function(err, user) {
if(err){
//do something with the error
}
console.log("user saved!: " user.id);
}
'Yieldified' this would look something like this:
var user = yield newUser.save();
console.log("user saved!: " user.id);
But how would I check for err
to exist, with the purpose of executing //do something with the error
?
Unfortunately generators suck for error handling. I mean checking errors manually on every step of the way and propagating them manually sucks too but not as much as the try-catch
statement in Javascript.
try {
var user = yield newUser.save();
console.log("user saved!: " user.id);
}
catch (e) {
//Abstract code that checks if the error is what you think it is
if (isFromNewUserSave(e)) {
}
else {
throw e;
}
}
The problem with try catch statement as you can see is that it catches everything. There is an additional problem in that errors that would be compiler errors in other languages are thrown in Javascript at runtime. But if you just use try catch without checks you will not see them at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With