Hapijs Custom 500 Error Page

Looking through the Hapi documentation and trying on Google, I can find how to set up a 404 page, but I can't find anything about setting up 500 pages.

I tried to add an error handler as follows:

server.on('internalError', function (request, err) {
    console.log("Internal Error:", err);
    request.reply.view('errors/500', {
        error: err
    }).code(500);
});

But my hook is never called. Is there an easy way to bring back a custom 500-page page using Hapijs?

+4
source share
1 answer

You need to catch the error response inside the extension function onPreResponseand install a new HTML response there.

The same principle applies to any Boom error, regardless of whether you installed it in the handler or set inside hapi (for example, 404 was not found or 401 was not resolved with an auth error.

, :

index.js

const Hapi = require('hapi');
const Path = require('path');

const server = new Hapi.Server();
server.connection({ port: 4000 });

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        reply(new Error('I\'ll be a 500'));
    }
});

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

    if (request.response.isBoom) {
        const err = request.response;
        const errName = err.output.payload.error;
        const statusCode = err.output.payload.statusCode;

        return reply.view('error', {
            statusCode: statusCode,
            errName: errName
        })
        .code(statusCode);
    }

    reply.continue();
});


server.register(require('vision'), (err) => {

    if (err) {
        throw err;
    }

    server.views({
        engines: {
            hbs: require('handlebars')
        },
        path: Path.join(__dirname, 'templates')
    });

    server.start((err) => {

        if (err) {
            throw err;
        }

        console.log('Server running at:', server.info.uri);
    });
});

/error.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>

    <style>
        body {
            text-align: center;
            background: #B0B0B0;
            color: #222;
        }
        .error h1 {
            font-size: 80px;
            margin-bottom: 0;
        }
    </style>
</head>
<body>
    <div class="error">
        <h1>&#x26a0;<br/>{{statusCode}}</h1>
        <h2>{{errName}}</h2>
    </div>
</body>
</html>

, http://localhost:4000/, :

enter image description here

, , hapi, . 4xx. http://localhost:4000/notapage, , 404:

enter image description here

+16

All Articles