Hapijs Custom 500错误页面

时间:2015-08-24 14:24:31

标签: node.js hapijs

浏览Hapi的文档,并尝试谷歌,我可以找到如何设置404页面,但我找不到任何关于设置500页的内容。

我尝试添加如下错误处理程序:

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

但我的钩子永远不会被召唤。有没有一种简单的方法可以使用Hapijs返回自定义500页?

2 个答案:

答案 0 :(得分:17)

您需要在onPreResponse扩展功能中捕获错误响应,并在那里设置新的HTML响应。

同样的原则适用于任何Boom错误,无论是由您在处理程序中设置还是由内部hapi设置(例如,404 Not found或401 Unauthorized from failed auth。

以下是您可以尝试的示例:

<强> 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

这种方法可以捕获任何Boom响应,包括由hapi内部而不是由我们生成的响应。因此也适用于4xx错误。尝试导航到http://localhost:4000/notapage,您将获得相同的漂亮页面,但是对于404:

enter image description here

答案 1 :(得分:0)

对于那些寻求与Hapi v17 +兼容的答案的人,相同的代码Child将被翻译为:

index.js

index.js
相关问题