Created
January 17, 2016 06:11
-
-
Save yandongxu/3def5c2f4120628f6be8 to your computer and use it in GitHub Desktop.
Hapi.js error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Hapi = require('hapi'); | |
const server = new Hapi.Server(); | |
server.connection({ port: 3000 }); | |
// routes | |
server.route(require('routes')); | |
// error handlers | |
server.ext('onPreResponse', (request, reply) => { | |
if (request.response.isBoom) { | |
// Inspect the response here, perhaps see if it's a 404? | |
return reply.redirect('/'); | |
} | |
return reply.continue(); | |
}); | |
// start server | |
server.start(err => { | |
if (err) throw err; | |
console.log(`Server running at: ${server.info.uri}`); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = [ | |
{ | |
method: 'GET', | |
path: '/user/{id}', | |
handler: (request, reply) => { | |
User | |
.findById(request.params.id) | |
.then(user => { | |
user | |
.getSubjects() | |
.then(subjects => { | |
reply(Object.assign({}, user.get(), { | |
subjects: subjects | |
})) | |
}); | |
}) | |
.catch(err => { | |
reply(Boom.notFound('User not exsit')); | |
}) | |
} | |
} | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment