2

私がエラーをスローした場合、エクスプレスは connect errorHandler ミドルウェアを使用して適切にレンダリングします。

exports.list = function(req, res){
  throw new Error('asdf');
  res.send("doesn't get here because Error is thrown synchronously");
};

そして、プロミス内でエラーをスローすると、それは無視されます (これは私には理にかなっています)。

exports.list = function(req, res){
  Q = require('q');
  Q.fcall(function(){
    throw new Error('asdf');
  });
  res.send("we get here because our exception was thrown async");
};

ただし、プロミス内でエラーをスローして「完了」ノードを呼び出すと、例外がミドルウェアによってキャッチされないため、ノードがクラッシュします。

exports.list = function(req, res){
  Q = require('q');
  Q.fcall(function(){
    throw new Error('asdf');
  }).done();
  res.send("This prints. done() must not be throwing.");
};

上記を実行した後、ノードは次の出力でクラッシュします。

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: asdf
    at /path/to/demo/routes/user.js:9:11

したがって、私の結論は、done() は例外をスローしているのではなく、別の場所で例外をスローするということです。そうですか?私がしようとしていることを達成する方法はありますか?約束のエラーはミドルウェアによって処理されますか?

参考までに: このハックはトップ レベルで例外をキャッチしますが、ミドルウェアの領域外であるため、私のニーズには合いません (エラーを適切にレンダリングするため)。

//in app.js #configure
process.on('uncaughtException', function(error) {
  console.log('uncaught expection: ' + error);
})
4

1 に答える 1

2

おそらく、非同期エラーの処理にはconnect-domainミドルウェアが役立つでしょう。このミドルウェアを使用すると、通常のエラーと同様に非同期エラーを処理できます。

var
    connect = require('connect'),
    connectDomain = require('connect-domain');

var app = connect()
    .use(connectDomain())
    .use(function(req, res){
        process.nextTick(function() {
            // This async error will be handled by connect-domain middleware
            throw new Error('Async error');
            res.end('Hello world!');
        });
    })
    .use(function(err, req, res, next) {
        res.end(err.message);
    });

app.listen(3131);
于 2012-12-08T00:52:22.003 に答える