node-error-handler

    1.2.3 • Public • Published

    node-error-handler

    npm Build Status codecov GitHub npm

    Installation

    $ npm install node-error-handler --save

    Use

    In an express based application:

    const  express = require('express');
    const  errorHandler = require('node-error-handler');
      
    const  app = express();
    
    // Setup your middlewares
    // Setup your routes
    app.get('/foo', (req, res, next) => {
      const  error = new  Error('Missing field(s): foo');
      error.code = 422;
      next(error);
    });
    
    // HTTP errorHandler
    app.use(errorHandler({ log: true, trace: true, camel_case: true }));

    Options

    Option Type Default Description
    log Boolean | Function false If true all errors are printed with stderr. If function use custom fuction defined by user.
    trace Boolean false If true the trace is attached to output.
    camel_case Boolean false If true The camelCase approach is used by error handler.

    Customizing log

    app.use(errorHandler({ log: saveErrorLogs }));
    
    function saveErrorLogs (err, obj, req) {
       // Do some stuff
    }

    Example

    5xx error camel_case: false:

    { "error": { "status_code": 500,"code": "INTERNAL_SERVER_ERROR" } }
    

    5xx error camel_case: true:

    { "error": { "statusCode": 500,"code": "INTERNAL_SERVER_ERROR" } }
    

    5xx error trace: false:

    { "error": { "status_code": 500,"code": "INTERNAL_SERVER_ERROR" } }
    

    5xx error trace: true:

    { "error": 
      { "status_code": 500,
        "code": "INTERNAL_SERVER_ERROR",
        "trace":   
        at Module._compile (internal/modules/cjs/loader.js:892:18)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
        at Module.load (internal/modules/cjs/loader.js:812:32)
        at Function.Module._load (internal/modules/cjs/loader.js:724:14)
        at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
        at internal/main/run_main_module.js:17:11 
        } 
    }
    

    Definition of a "Error"

    The error could contain the following fields:

    Error Key Purpose
    status_code HTTP status code for response. Default value: 500 (Internal Server Error).
    message Error message.
    code Error code.
    trace Error trace including data such as file paths, URLs.

    License

    MIT

    Install

    npm i node-error-handler

    DownloadsWeekly Downloads

    32

    Version

    1.2.3

    License

    MIT

    Unpacked Size

    15.5 kB

    Total Files

    13

    Last publish

    Collaborators

    • leonardofurnielis