npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@grupojaque/error-handler-js

v1.0.1

Published

Error handler for node

Downloads

12

Readme

ErrrorHandler

Handles errors thrown in the app and formats an HTTP response using customized functions.

Setup

Initialization

Install with:

$ npm i @grupojaque/error-handler-js

Require the module with the custom configuration:

ErrorHandler = require('@grupojaque/error-handler-js')(configJson);

Configuration

Configuration object

The following values can be passed as configuration to configure the module.

| Key | Description | | ---- | ----------- | | httpCodes | An object with http status names as keys and the corresponding code as value. Most errors are already defined as defaults| | logging | Indicates the logger, or false for no logs| | beforeResponse | Function to define what you want to do before responding | | customizeBody | Function to customize the response body | | constructors | Object to map possible errors to an ErrorHandler construction. The keys must be the name or code of the specific error |

You can find a configuration example file here

Usage

Constructor

ErrorHandler(status, message, errors)

Creates a new error handler.

  • status: Name or code of HTTP status
  • message: Message to send in the response, can be transalated in customBody function.
  • errors: Array containing the desglosed errors. Used for field errors, each one must have the array fields indicating the names of the wrong fields and a message. Empty array by default.
  • errorDetail: Additional custom details of error. Can be an array containing translation info.

Example:

throw new ErrorHandler('forbidden', 'without_permissions');

Example with fields:

throw new ErrorHandler(422, 'invalid_format', [{fields:['email'], message:'not_valid_email'}] );

Example with detail info:

throw new ErrorHandler(422, 'size_big', [{fields:['email'], message:'not_valid_email'}], ['size_big',12,13] );

Negotiate

The negotiate function is exposed as static, this function will recieve a request and response object and return another function that be waiting for an error to be passad to be handeled and redponded acordingly. Once the function will the error is called will do the following:

  1. If the error is not an error created with the ErrorHandler constructor, it will call a function to create an ErrorHandler object from the error. This function will try to do the creation by using the constructors definend in the configuration.
  2. Will generate a body with the arguments:
  • errors Array with field errors
  • message Message of the error This body will go through the customizeBody function defined in the configuration.
  1. Will call the beforeResponse function defined in the configuration.
  2. Will respond using the response object and the configurated body.

Any errors in this process will throw a serverError.

Controller

To use this function in the controller, any error must be redirected to the negotiate function to be handled.

Example:

get: function(req, res) {
  return Model.findAll()
    .then(res.ok)
    .catch(ErrorHandler.negotiate(req, res));
    //.catch(res.negotiate); For sails
}

Mapping errors

The mapErrors function will map the errors thrown, to an specified construction different to the one configured, by using the error name.

Example:

get: function(req, res) {
  return Model.findById(id)
    .then(res.ok)
    .catch(ErrorHandler.mapErrors(
      {
        DataBaseError: new ErrorHandler('serverError','database_error')
      }      
    ))
    .catch(ErrorHandler.negotiate(req, res));
    //.catch(res.negotiate); For sails
}

Salis JS

If using sails must do the following configurations.

Import the module in the bootstrap.js file and set ErrorHandler as global.

The responses folder must be modified for all the responses to go through
negotiate. Success response files must be kept along with the following files to handle errors.

  • api/responses/serverError.js

Redirects all errors to negotiate

module.exports = function serverError(err) {
  const res = this.res;

  return res.negotiate(err);
};
  • api/responses/notFound.js

Redirects route not found to negotiate, with custom error.

module.exports = function notFound() {
  const res = this.res;

  res.negotiate(new ErrorHandler('notFound', 'route_not_found'));
};
  • api/responses/negotiate.js

Manages all errors in negotiate using the ErrrorHandler object returned in the import.

module.exports = function negotiate(error) {
  return ErrorHandler.negotiate(this.req, this.res)(error);
};

Contributors