从 hapi 插件内部抛出时,控制台中没有显示错误

No error shown in console when thrown from inside hapi plugin

出于某种原因,当我使用 nodemon 启动我的 hapi 服务器并导航到 http://localhost:3000/hapi-ext-fetch 时,服务器控制台中没有显示任何错误,这使得调试变得非常困难。这是我的代码:

var Hapi = require('hapi');
var Joi = require('joi');
var fetch = require('isomorphic-fetch');

var debugMode = { debug: { request: [ 'error', 'request-internal' ] }};
var server = new Hapi.Server(debugMode);

server.connection({ port: 3000 });

var myPlugin = {
  register: function (server, options, next) {
    server.route([
      {
        method: 'GET',
        path: '/{name}',
        handler: function ( request, reply ) {
          throw new Error('this error isnt shown!');
        },
        config: {
          validate: {
            params: {
              name: Joi.string().min(3).max(10)
            }
          }
        }
      }
    ]);
    next();
  }
};

myPlugin.register.attributes = {
  name: 'myPlugin',
  version: '1.0.0'
};

server.register([
  {
    register: myPlugin,
    routes: {
      prefix: '/test'
    }
  }
], function() {
  server.ext( 'onPreResponse', ( request, reply ) => {
    if ( typeof request.response.statusCode !== 'undefined' ) {
      return reply.continue();
    }
    fetch('http://localhost:3000/test/whatever')
    .then(function(result) {
      reply(result);
    })
    .catch(function(err) {
      reply('error on server side: ' + err.stack);
    });
  });

  server.start((err) => {
    if (err) {
      throw err;
    }
    console.log('Server running at:', server.info.uri);
  });
});

我正在使用 hapi 13.0.0

不能说我完全理解你在这里的用例,也不能说这个问题对其他人有帮助。但是你想要做的似乎是:

  • 向 /hapi-fetch-ext 发送请求
  • 有那个请求 404
  • 然后在 onPreResponse 中获取另一条路线 /test/whatever
  • 希望看到"this error isn't shown error"

不确定您是否知道,但这将导致请求的无限循环(您的提取将导致另一个 onPreResponse 等等)。所以你应该只去获取 404:

server.ext( 'onPreResponse', ( request, reply ) => {

    if (request.response.isBoom && request.response.output.statusCode === 404) {
        return fetch('http://localhost:3000/test/whatever')
        .then(function(result) {
            reply(result);
        })
        .catch(function(err) {
            reply('error on server side: ' + err.stack);
        });
    }

    return reply.continue();
});