Skip to content
This repository has been archived by the owner on Jul 22, 2022. It is now read-only.

Node/Express error handling middleware for JSON:API errors.

Notifications You must be signed in to change notification settings

kioannou/express-json-api-error-handler

Repository files navigation

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:

$ 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
{
  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)

Error structure

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',
      },
    };

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

import { AuthError } from `express-json-api-error-handler`;

next(new AuthError('The user is not authorized!', 5555))

Test

npm install

npm test

All feedback, issues or suggestions are welcomed :)

About

Node/Express error handling middleware for JSON:API errors.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published