funktionswerk / hapi-i18n

Translation module for hapi based on mashpie's i18n module
MIT License
39 stars 22 forks source link

Not working on custom error page #10

Closed minustime closed 7 years ago

minustime commented 7 years ago

I integrated this plugin on my site and works perfectly, however my custom 404 error page generates an internal error:

__ is not a function: templates/404.pug:2

Looks like the onPreResponse part of the plugin never gets called, thus the view doesn't know what __ is.

server.js

const Hapi = require('hapi');
const server = new Hapi.Server();

server.connection({
    host: 'localhost',
    port: 8000
})

const plugins = [
    {
        register: require('vision')
    },
    {
        register: require('hapi-i18n'),
        options: {
            locales: 'de',
            defaultLocale: 'de',
            directory: __dirname + '/i18n',
            updateFiles: false,
        }
    }
];

server.register(plugins, err => {
    server.views({
        engines: {
            pug: require('pug')
        },
        path: 'templates'
    });
});

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

    const response = request.response;

    if(!response.isBoom) {
        return reply.continue();
    }

    return reply.view('404');
});

server.route({
    method: 'GET',
    path: '/',
    handler: (request, reply) => {
        return reply.view('home');
    }
});

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

404.pug

h1 This is the 404 page
h2 #{__('Hello World!')}

Please see a complete example here: https://github.com/minustime/hapijs-localization-test

funktionswerk commented 7 years ago

The variety in case of an error response is not 'view' (it is undefined), so the response object is not extended with the template helper. Also, the 'onPreAuth' extension point is not called in case of an error. Can you use another strategy to handle your 404 errors?

minustime commented 7 years ago

The way I implemented the error page is the one outlined in their API docs:

When a different error representation is desired, such as an HTML page or a different payload format, the 'onPreResponse' extension point may be used to identify errors and replace them with a different response object.

I'll think of an alternative solution, but I think this issue will trip other users of the plugin.

(Thanks for making this plugin available btw!)

funktionswerk commented 7 years ago

The problem is that the 'onPreAuth' extension point is not called. If I use the 'onRequest' extension point (which is called in case of an error) the request object is lacking the language code.

I am sorry but I guess I can't help you out here. If you have a working solution feel free to create a pull request.