Fouad
Fouad

Reputation: 855

javascript async/await unhandledRejection not triggered

I am developing a RESTful API using HapiJS.

I'm using HapiJS v17 to take advantage of async/await.

My Intentions is to not handle exceptions in each route but to have a centralized place to handle all unhandledRejection.

The way I'm trying to achieve this is by listening to the unhandledRejection event early when the server starts.

process.on('unhandledRejection', (reason, p) => {
    console.log('Unhandled Rejection at:', p, 'reason:', reason);
});

And then for example, in my business logic code, I intentionally do not catch rejected promises(for example a database error) hoping that I will be able to process it in the callback of process.on('unhandledRejection'

But the console.log statement is never triggered.

For example:

handler: async (request, h) => {
            const user = request.user;

            const userIdToUpdate = request.params.id;

            const firstName = request.payload.firstName;
            const lastName = request.payload.lastName;
            const roles = request.payload.roles;

            const updatedUser = await UserCtrl.updateUser(userIdToUpdate, firstName, lastName, roles, user.tenantId.toString());

            const response = h.response(updatedUser.sanitize());
            response.type('application/json');
            return response;
        }

UserCtrl.updateUser returns a Promise, let's say the database connection is down, I'm assuming that the Promise should be rejected but why is the process.on('unhandledRejection', (reason, p) => { is not being triggered?

Upvotes: 0

Views: 1014

Answers (2)

Fouad
Fouad

Reputation: 855

I ended up implementing a PreResponse hook that will check if the response is an Error and act accordingly

server.ext('onPreResponse', (request, h) => {
            const response = request.response;
            if (!response.isBoom) {
                return h.continue;
            }

            let error = response;
            if (!error.message && error.output && error.output.payload) {
                return error.output.payload;
            }

            error = new Error(error.message);
            return Boom.boomify(error, {statusCode: 400});
        });

Upvotes: 0

udalmik
udalmik

Reputation: 7998

I think HapiJS catches error of your request handler.

Looking at the code - seems error catched there.

Not sure in what format and under what conditions it is rethrown further.

I would not rely on framework for such logic anyway and at least wrap all handlers with own wrapper and log all errors there.

Upvotes: 1

Related Questions