jaz
jaz

Reputation: 121

No error shown in console when thrown from inside hapi plugin

For some reason no error shows up in the server console when I start my hapi server with nodemon and navigate to http://localhost:3000/hapi-ext-fetch and this makes debugging very difficult. Here is my code:

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);
  });
});

I'm using hapi 13.0.0

Upvotes: 0

Views: 529

Answers (1)

Matt Harrison
Matt Harrison

Reputation: 13567

Can't say I totally understand your use case here and if this question will be helpful to other people. But what you're trying to do it seems is:

  • Send a request to /hapi-fetch-ext
  • Have that request 404
  • And then in an onPreResponse go fetch another route /test/whatever
  • Hope to see the "this error isn't shown error"

Not sure if you're aware but this is going to cause an infinite cycle of requests (your fetch will cause another onPreResponse and so on and so on). So you should probably only go fetch on a 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();
});

Upvotes: 1

Related Questions