首页 文章

Hapijs Custom 500错误页面

提问于
浏览
4

通过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页面?

1 回答

  • 16

    您需要在 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);
        });
    });
    

    templates/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;
    {{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

相关问题