A utility to convert Objection database errors into Boom HTTP errors
Note
Avocat is intended for use with hapi v19+, nodejs v12+, and Objection v2 or v3 (see v1 for lower support).
Throws a Boom error according to the Objection error received.
error
- the Objection error (any other types of errors are just ignored).options
- optional object where:return
- iftrue
will return the error instead of throwing it.includeMessage
- iftrue
the Boom error created will preserve the Objection error message.
These are the error mappings maintained by Avocat:
NotFoundError
→ 404 Not FoundValidationError
→ 400 Bad RequestNotNullViolationError
→ 400 Bad RequestConstraintViolationError
→ 400 Bad RequestForeignKeyViolationError
→ 400 Bad RequestDataError
→ 400 Bad RequestCheckViolationError
→ 400 Bad RequestUniqueViolationError
→ 409 ConflictDBError
→ 500 Internal Server Error
'use strict';
const Hapi = require('@hapi/hapi');
const Avocat = require('@hapipal/avocat');
const User = require('./user-model'); // An Objection model bound to a knex instance
const server = Hapi.server();
server.route({
method: 'get',
path: '/users/{id}',
handler(request) {
try {
return await User.query()
.findById(request.params.id)
.throwIfNotFound();
}
catch (err) {
Avocat.rethrow(err); // Throws a 404 Not Found if user does not exist
throw err;
}
}
});