Vidur Singla
Vidur Singla

Reputation: 305

Error handling in HAPI

Catch all and any errors in a hapi request lifecycle. I have a signup handler,

public signup(request: Hapi.Request, reply: Hapi.Base_Reply) {
    this.database.user.create(request.payload).then((user: any) => {
        return reply({
            "success": true
        });
    }).catch((err) => {
        reply(Boom.conflict('User with the given details already exists'));
    });
}

Now, I am catching the error, but I can't be always sure that I will get this error message only. What if there is an error in the database? How to catch such database errors or any other unknown errors for all the requests. ???

Upvotes: 1

Views: 3340

Answers (2)

Vidur Singla
Vidur Singla

Reputation: 305

I figured out a way to handle such errors in Hapi. What I was looking for was a PreResponse handler. Now, the PreResponse handler can log all the errors and I can throw a 500 error response.

What I am saying is by simply writing

reply(err)

I can send a 500 error and can catch this error using preResponse handler. Something like this,

server.ext('onPreResponse', (request: Hapi.Request, reply: Hapi.ReplyWithContinue) => {
        const response = request.response;
        if (!response.isBoom) { // if not error then continue :)
            return reply.continue();
        }
        console.log(response);
        return reply(response);
    });

Upvotes: -1

Yoel Monzon
Yoel Monzon

Reputation: 111

Maybe you have to return the err.message in your reply like

reply(Boom.conflig(err.message))

or if you want to manage or manipulate the error you have to verify the type of error like

if (err instanceof DatabaseError) {
   // manage database error
}

Upvotes: 0

Related Questions