Socket
Socket
Sign inDemoInstall

error-generator

Package Overview
Dependencies
0
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    error-generator

Easily create and manage errors for any API.


Version published
Weekly downloads
12
increased by1100%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

Error Generator

Error Generator is an error generation node module for easily creating and managing errors you plan on using in your application. One common use case for Error Generator is creating errors which are sent in an Express JS response. Error Generator is lightweight, fast, and has no dependencies.

Error Generator provides the following functionality:

  • Manages your list of errors
  • Create new errors to manage
  • Generate an instance of a stored error
  • Special: Express JS response function to send an error

Installation

npm install --save error-generator

Examples

// Registering a new error
const errorGenerator = require('error-generator');
errorGenerator.registerError('not_found', {
  status_code: 404,
  message: 'The requested resource was not found on the server.',
  use_source: true
});
// Sending an error in an Express route
const express = require('express');

let app = express();
app.use(errorGenerator.errorGenerator);

app.get('/', (req, res) => {
  res.sendError('not_found', {
    source: {
      parameter: 'email_address',
        value: null
    }
  });
});

// Returns
{
  "name": "not_found",
  "status_code": 404,
  "message": "The requested resource was not found on the server.",
  "source": [{
    parameter: 'email_address',
    value: null
  }]
}

API

errorGenerator.registerError(name, options)

Registers a new error with the given name and options.

  • name - Name of the error to register

  • options - Options that can be used for the error

    • options.status_code - Status code for Express to send in the response
    • options.message - Message for Express to send in the response
    • [options.use_source] - Error will be attached to some source values which must be specified
    • [options.use_timestamp] - Timestamp of the error will be attached (uses new Date() internally)
    • [options.logging] - Function which will be called to log the error, includes a timestamp
    • [options.callback] - Callback to call when an instance of the error is created
    • [options.*] - Any extra options will be attached to the error

errorGenerator.getError(name)

Returns a registered error with its options if the error exists. Returns undefined otherwise.

  • name - Name of the error to get

errorGenerator.on(name, callback)

Attaches a callback to an error, which will be called with the return value of the createError call. Can be called multiple times to add more callbacks to the error.

  • name - Name of the error to attach the callback to
  • callback - Callback to call when the error is created using createError

errorGenerator.off(name, callback)

Detaches a callback from an error so that it will no longer call on invocation of createError. If all callbacks are detached from an error, the callback property will be removed.

  • name - Name of the error to detach the callback from
  • callback - Reference to the callback to remove from the callbacks list

Note: If you plan on removing a callback from an error make sure to keep a reference to it. We remove callbacks based on an equal reference using ==.

errorGenerator.clearError(name)

Clears an error out of the error list. Returns the error that was removed.

  • name - Name of the error to remove from the list

errorGenerator.clearErrors()

Clears all of the errors out of the error list.

errorGenerator.createError(name[, options])

Creates the error object that will be sent in the response of the Express response. In the case that you don't use Express, you can always use this method to create the error to send yourself.

  • name - Name of the error to create

  • [options] - Options that can be used for the error

    • [options.message] - Message to overwrite and use once, does not replace the error's message
    • [options.source] - Required if error was created with use_source option, represents the value(s) that was in error

Note: If you plan on attaching a source of undefined, it is recommended to use arrays to avoid any complication. One common use-case for this is when a user calls an API point with missing data.

errorGenerator.bulkCreateErrors(errors, options)

Creates multiple errors using createError repeatedly internally. Useful when, for example, a user forgets to submit both their email address and password and you want to display an error for each.

  • errors - Array of valid error objects that will each pass through createError on their own

  • options - Options that can be attached to the errors

    • options.message - Message that must be provided to summarize the list of errors
    • options.status_code - Status code that reflects the overall error (individual status codes are removed)
    • options.* - Any further option is simply attached to the error as extra information

errorGenerator.errorGenerator()

Attaches the function sendError to an Express response. Should be used when first setting up the Express application. See the example above for usage.

res.sendError(name[, options]) - from Express

Follows the same API as createError, see above. Sends the response with the status code attached to the error along with the contents of the error.

Also follows the API of bulkCreateErrors, which means that you can either send one or multiple errors. The options in this case follow the options of bulkCreateErrors, and the status code used for the overall error will be used at the status code of the response.

Contributing

This project was built using Babel Stage 2. I am open to anyone who wishes to fork the project and create new test cases, add useful functionality, or anything else. I use this project in my own work so I will be adding to this library as functionality arises that I need.

All I ask is that if you add functionality please provide the necessary test cases and try to get as high code coverage as possible.

Roadmap

I am currently interested in adding more Express middleware for doing validation of request data and sending Error Generator errors in the case of a failure. My ideal setup would look something like:

// Error middleware
const router = require('express').router;
const errorGenerator = require('error-generator');

router.get(
  '/',
  errorGenerator.verify({
    params: [{
      name: 'user_id',
      number: true,
      error: 'invalid_parameter'
    }],

    body: [{
      name: 'first_name',
      text: true,
      error: 'invalid_parameter'
    }]
  }),
  function updateUser(req, res) { ... }
)

Keywords

FAQs

Last updated on 09 Feb 2016

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc