项目作者: kioannou

项目描述 :
Node/Express error handling middleware for JSON:API errors.
高级语言: TypeScript
项目地址: git://github.com/kioannou/express-json-api-error-handler.git
创建时间: 2018-12-12T13:57:11Z
项目社区:https://github.com/kioannou/express-json-api-error-handler

开源协议:

下载


code style: prettier
Build Status
codecov

Express JSON:API Error Handler

Error handling middleware for Node/Express applications. All detected errors are finally transformed into JSON:API errors.

Installation

Installation is done using the
npm install command:

  1. $ npm i express-json-api-error-handler

Features

ErrorHandler

The library exposes the ErrorHandler which uses:

  1. The handle method as the express middleware
  2. The setErrorEventHandler method for setting a callback when an error is raised
  3. You can initialize with setting options. The available options for now are
    1. {
    2. buildMeta: boolean // To build the meta of the error not. Defaults to false.
    3. }

Example on how to initialize the event handler

  1. import { ErrorHandler } from `express-json-api-error-handler`;
  2. const errorHandler = new ErrorHandler({ buildMeta: true});
  3. errorHandler.setErrorEventHandler((err) => { console.log(err)})
  4. app.use(errorHandler.handle)

Error structure

The error the handler produces is of the following structure

  1. {
  2. 'errors': [
  3. {
  4. 'code': '1200',
  5. 'detail': 'Mock error description',
  6. 'status': '403',
  7. 'title': 'Error 403',
  8. },
  9. ],
  10. 'jsonapi': {
  11. 'version': '1.0',
  12. },
  13. 'meta': {
  14. 'request_id': '12345',
  15. },
  16. };

Errors

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

  1. import { AuthError } from `express-json-api-error-handler`;
  2. next(new AuthError('The user is not authorized!', 5555))

Test

npm install

npm test

All feedback, issues or suggestions are welcomed :)