0

私は次のようなコードを持っています:

app.js

app.use(app.router)
app.use(function(err, req, res, next) {
  res.render(errorPage)
})

app.get('/', function(req,res,next) {
  module1.throwException(function{ ... });
});

module1.js

exports.thowException = function(callback) {
       // this throws a TypeError exception.
       // follwoing two lines are getting executed async
       // for simplicity I removed the async code
       var myVar = undefined;
       myVar['a'] = 'b'
       callback()
}

module1.js の例外を除いて、私のノード prcoess は停止します。代わりに、エラーページをレンダリングしたかったのです。

app.get(..) で try ... catch を試してみましたが、役に立ちませんでした。

これどうやってするの??

4

1 に答える 1

0

try ... catch非同期コードでは使用できません。この記事では、node.js でのエラー処理に関するいくつかの基本原則を見つけることができます。あなたの状況では、エラーをスローするのではなく、モジュールからのコールバックの最初のパラメーターとしてエラーを返し、次にエラーハンドラーを呼び出す必要があります。エラー処理関数は app.route ハンドラーの直後にあるため、ルートのいずれかが一致しない場合は、Not Found エラーも確認する必要があります。次のコードは非常に単純化された例です。

app.js

app.use(app.router)
app.use(function(err, req, res, next) {
  if (err) {
    res.render(errorPage); // handle some internal error
  } else {
    res.render(error404Page); // handle Not Found error
  }
})

app.get('/', function(req, res, next) {
  module1.notThrowException(function(err, result) {
    if (err) {
      next(new Error('Some internal error'));
    }
    // send some response to user here
  });
});

module1.js

exports.notThrowException = function(callback) {
  var myVar = undefined;
  try {
    myVar['a'] = 'b';
  } catch(err) {
    callback(err)
  }

  // do some other calculations here 

  callback(null, result); // report result for success
}
于 2013-08-10T09:30:31.077 に答える