Node/Express error handling middleware for JSON:API errors.
Error handling middleware for Node/Express applications. All detected errors are finally transformed into JSON:API errors.
Installation is done using thenpm install
command:
$ npm i express-json-api-error-handler
ErrorHandler
The library exposes the ErrorHandler
which uses:
handle
method as the express middlewaresetErrorEventHandler
method for setting a callback when an error is raised
{
buildMeta: boolean // To build the meta of the error not. Defaults to false.
}
Example on how to initialize the event handler
import { ErrorHandler } from `express-json-api-error-handler`;
const errorHandler = new ErrorHandler({ buildMeta: true});
errorHandler.setErrorEventHandler((err) => { console.log(err)})
app.use(errorHandler.handle)
The error the handler produces is of the following structure
{
'errors': [
{
'code': '1200',
'detail': 'Mock error description',
'status': '403',
'title': 'Error 403',
},
],
'jsonapi': {
'version': '1.0',
},
'meta': {
'request_id': '12345',
},
};
The library provides some errors you can use in you app.
The available errors are AuthError
, ForbiddenError
, InternalServerError
, NotFoundError
.
You can use them like this
import { AuthError } from `express-json-api-error-handler`;
next(new AuthError('The user is not authorized!', 5555))
npm install
npm test
All feedback, issues or suggestions are welcomed :)