您需要在 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>⚠<br/>{{statusCode}}</h1>
<h2>{{errName}}</h2>
</div>
</body>
</html>
转到http://localhost:4000/ 以查看您的自定义错误页面进行测试:
这种方法可以捕获任何 Boom 响应,包括那些由 hapi 而不是我们内部生成的响应。因此也适用于 4xx 错误。尝试导航到http://localhost:4000/notapage,您将获得相同的漂亮页面,但显示的是 404: