title: Handle NodeJS error event?
body: <p>I have a worker class that has lots of different utility methods, and emits <code>error</code> messages when there's a problem anywhere in the execution. Due to NodeJS magic, <code>error</code> messages are special, and if nothing is listening to them, they're turned into thrown Errors, so I currently do:</p>
  
  <pre><code>var myWorkerFunction = function(input) {
    var w = myFactory();
    try {
      w.dothis();
      w.dothat(input);
      w.hokeypokey();
      return w.finalize();
    } catch(e) {
      return false;
    }
  }
  </code></pre>
  
  <p>What I wonder though, is it possible to avoid the try/catch block entirely? NodeJS's documentation seems to indicate it's best to avoid not re-throwing a caught exception (I'm doing no checks here to see that it really was my worker's logic that threw the exception and not a critical fault from Node).</p>
  
  <p>So I'd like to do something like:</p>
  
  <pre><code>var myWorkerFunction = function(input) {
    var w = myFactory();
    w.on('error', function() {
      // How to tell caller of myWorkerFunction() I failed, 
      //   and stop the rest of the myWorkerFunction function? (return false)
    });
    w.dothis();
    w.dothat(input);
    w.hokeypokey();
    return w.finalize();
  }
  </code></pre>
  
  <p>But how to trigger that "return" for <code>myWorkerFunction</code> inside that event listener function? I could have <code>myWorkerFunction</code> emit an "error" message too, but that just kicks the can to the next layer, and doesn't stop the execution of the worker script (i.e. if <code>dothis()</code> fails, don't keep going and call <code>dothat(input)</code>). Is there a programming pattern for situations like this?</p>
  
  <p>EDIT: The one solution I could come up with is something like:</p>
  
  <pre><code>var myWorkerFunction = function(input) {
    var w = myFactory();
    var hasFailed = false;
    w.on('error', function() {
      hasFailed = true;
    });
    w.dothis();
    if (hasFailed) return fa;se
    w.dothat(input);
    if (hasFailed) return false;
    w.hokeypokey();
    if (hasFailed) return false;
    var out = w.finalize();
    if (hasFailed) return false;
    return out;
  }
  </code></pre>
  
  <p>Which is not very elegant having to constantly check if we've failed or not before every line of code.</p>