Member-only story

Server-Side Development with Hapi.js — Throwing Errors

John Au-Yeung
3 min readFeb 21, 2021

--

Photo by Fernando Brasil on Unsplash

Hapi.js is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Hapi.js.

Throw Unauthorized Errors

We can throw unauthorized errors with the @hapi/boom module.

It has the Boom.unauthorized method to throw the error.

For instance, we can write:

const Hapi = require('@hapi/hapi');
const Boom = require('@hapi/boom');
const init = async () => {
const server = new Hapi.Server({
port: 3000,
host: '0.0.0.0'
});
server.route({
method: 'GET',
path: '/',
handler(request, h) {
throw Boom.unauthorized('invalid password');
}
});
await server.start();
console.log('Server running at:', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();

We call Boom.unauthorized method with a message to create the 401 response.

Now we should get:

{"statusCode":401,"error":"Unauthorized","message":"invalid password"}

--

--

No responses yet