@grupojaque/error-handler-js

Error handler for node

Usage no npm install needed!

<script type="module">
  import grupojaqueErrorHandlerJs from 'https://cdn.skypack.dev/@grupojaque/error-handler-js';
</script>

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