hapi.js - Friendly error pages with extension events

Mike Frey
InstructorMike Frey
Share this video with your friends

Social Share Links

Send Tweet

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.

[00:01] My handler is replying with an error. By default, Hapi responds with JSON output for the error, but I'd prefer to show a friendlier error message with HTML.

[00:10] I've already got the Vision plugin registered and views configured. I could just use the view method and my error template to reply with HTML, but I'd really like a solution that will work across all of my routes that may reply with an error for any reason.

[00:26] To do that, I'll register an extension event on my Hapi server that watches for the on pre-response event. The request argument has a response property that contains details about how the route handler replied to the request. If the response is an error of any kind, Hapi converts it to a Boom object. It will have an is Boom property set to true.

[00:50] For my purposes, if is Boom is falsey, I want Hapi to continue processing the response normally by calling reply.continue. That means anything that passes this point is an error and I'll use reply.view to render an error template. Passing in resp.output.payload will give the template access to the status code and error message.

[01:13] Inside the error handle bars file, the status code and error message will print out in an H1. Now when I save and refresh the page, the JSON output is replaced by the rendered error template.

[01:25] But, because I replaced the response with new content, the status code is now set to 200, which is incorrect. It should be the same status code that is provided by the error. To update the status code to match the message, I can call the code function chained off of the reply.view call and pass up the status code from the error.

[01:46] Now the status code will be set correctly. If I change the error type from bad request to not found, the message and status code both reflect the correct error type.