Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for error when using yield instead of node-style callback?

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?

like image 824
Geert-Jan Avatar asked Dec 30 '13 19:12

Geert-Jan


1 Answers

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.

like image 193
Esailija Avatar answered Sep 20 '22 01:09

Esailija