bo-tech

heart and tech with love.

expressjsのres, next, errの挙動を確認してみた

今さら感のある実験(ExpressJS)

res, next, errの動きってどうなるの?

疑問があったのでendpointを一つ作って試し打ち。

router.get('/test/abc', function(req, res, next) {
   console.log('a');
   next();
 }, function(req, res, next) {
   console.log('b');
   res.status(200).json({ms:'ms1'});
   setTimeout(next, 10000);
 }, function(req, res, next) {
   console.log('c');
   res.status(200).json({ms:'ms3'});
   next(new Error('hogehoge'));
 }, function(req, res, next) {
   console.log('d');
 }, function(err, req, res, next) {
   console.log('e');
   console.log(err);
   res.status(400).json(err);
 });

これをベースにして入れ替えたり書き換えたりして実験。

ポイントは

  • resした後のfunctionは実行されるのか
  • nextの引数に何か渡した場合は直後のやつは呼ばれるのか
  • timeoutで設定しても大丈夫か
  • 二回resするとどうなるのか

ちなみに上記結果は

a
b
c
e
[Error: hogehoge]
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: write after end
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15)
    at ServerResponse.res.write (/home/vagrant/webapp/node_modules/compression/index.js:94:17)
    at ServerResponse.res.end (/home/vagrant/webapp/node_modules/compression/index.js:111:14)
...

このようになる。

ということで先ほどのポイントそれぞれに対しては以下のように整理した。

  • resした後のfunctionは実行されるのか

    res.jsonやres.sendしてもその後の関数は実行される。 (cが表示されているので)

  • nextの引数に何か渡した場合は直後のやつは呼ばれるのか

    nextに引数を渡してcallすると直後のerrorハンドリングができる関数へ遷移する。

    この部分はdocsでも記載されているから予想通り。

  • timeoutで設定しても大丈夫か

    特に問題なくresponseを返してから処理を行っているのが確認できた。

  • 二回resするとどうなるのか

    二回responseに対してwriteを行うとexceptionが発生する。

    これも大概予想通り。たまにasyncを実装していて間違った実装すると出てくる。

とこんな感じにまとまった。 一応備忘録的に。