同步函数很简单
try { // statements to try
        json = JSON.parse(body);    
        log('json:', json.groupnumberlimit, json.uuid);
    } catch (e) {
        dealerrors(e); // pass exception object to error handler -> your own function
        return;
    }

简单的说就是try catch就好了.

异步函数也很简单
let x = fs.createReadStream(path);
x.on('error', function (err) {
    log("err:", err);
    return;
})
x.pipe(res);

简单地说, 异步函数要去响应error事件, 不能try catch.

链式写法:

fs.createReadStream(path).on('error', function (err) {
            log("err:", err);
            return;
        }).pipe(res)
//但是如果把pipe写到onerror前面就不可以了.
异步函数可能会很复杂
a.pipe(b).pipe(c).on('error', function(e){handleError(e)});// 这么写是错的.

//下面这种写法是正确的.
a.on('error', function(e){handleError(e)})
.pipe(b)
.on('error', function(e){handleError(e)})
.pipe(c)
.on('error', function(e){handleError(e)});

//这么写也是正确的:
a.on('error', handler)
b.on('error', handler)
c.on('error', handler)

a.pipe(b).pipe(c)

正解出现了, 用js的函数阈(闭包)解决问题

var d = domain.create();
 d.on('error', handleAllErrors);
 d.run(function() {
     fs.createReadStream(tarball)
       .pipe(gzip.Gunzip())
       .pipe(tar.Extract({ path: targetPath }))
       .on('close', cb);
 });

参考:

  • https://stackoverflow.com/questions/21771220/error-handling-with-node-js-streams

  • https://github.com/jabez128/stream-handbook

剧情翻转了.
  • node官方设置domain是废弃的内容. : https://nodejs.org/api/domain.html
  • 用啥还没定: https://github.com/nodejs/node/issues/10843
  • https://stackoverflow.com/questions/7310521/node-js-best-practice-exception-handling