[Hapi.js] Friendly error pages with extension events

hapi automatically responds with JSON for any error passed to a route's reply()method. But what if your application needs errors rendered in HTML? This lesson shows how to implement friendly HTML error messages using hapi extension events.

const Hapi = require( 'hapi' )
const Boom = require( 'boom' )
const server = new Hapi.Server()
server.connection( { port: 8000 } ) server.register(require('vision'), function(request, reply){
server.views({
engines: { hbs: require('handlebars') },
relativeTo: __dirname,
path: 'views'
}); server.ext('onPreResponse', function(request, reply){
var resp = request.response;
// if there is an error
if (resp.isBoom) {
return reply.view('error', resp.output.payload)
// change the status code
.code(resp.output.statusCode);
}
reply.continue()
})
}) server.start( function (err) {
if (err) {
throw err;
}
console.log( 'Started at:', server.info.uri )
} );
上一篇:PHP IDE 框架 服务器 相关


下一篇:JavaWeb基础-servlet