Code Monkey home page Code Monkey logo

strong-error-handler's Introduction

strong-error-handler

OpenSSF Best Practices OpenSSF Scorecard Continuous Integration CodeQL

This package is an error handler for use in both development (debug) and production environments.

In production mode, strong-error-handler omits details from error responses to prevent leaking sensitive information:

  • For 5xx errors, the output contains only the status code and the status name from the HTTP specification.
  • For 4xx errors, the output contains the full error message (error.message) and the contents of the details property (error.details) that ValidationError typically uses to provide machine-readable details about validation problems. It also includes error.code to allow a machine-readable error code to be passed through which could be used, for example, for translation.

In debug mode, strong-error-handler returns full error stack traces and internal details of any error objects to the client in the HTTP responses.

Supported versions

This module adopts the Module Long Term Support (LTS) policy, with the following End Of Life (EOL) dates:

Version Status Published EOL
4.x Current Oct 2020 Apr 2023 (minimum)
3.x Active LTS Jun 2018 Dec 2022
2.x End-of-life Mar 2017 Oct 2020

Learn more about our LTS plan in the LoopBack documentation.

Installation

$ npm install --save strong-error-handler

Use

In an Express-based application:

var express = require('express');
var errorHandler = require('strong-error-handler');

var app = express();
// setup your routes
// `options` are set to default values. For more info, see `options` below.
// app.use(errorHandler({ /* options, see below */ }));
app.use(errorHandler({
  debug: app.get('env') === 'development',
  log: true,
}));

app.listen(3000);

The module also exports writeErrorToResponse, a non-middleware flavor of the error handler:

const http = require('http');
const writeErrorToResponse = require('strong-error-handler')
  .writeErrorToResponse;
const errHandlingOptions = {debug: process.env.NODE_ENV === 'development'}

http
  .createServer((req, res) => {
    if (errShouldBeThrown) {
      writeErrorToResponse(
        new Error('something went wrong'),
        req,
        res,
        errHandlingOptions,
      );
    }
  })
  .listen(3000);

In LoopBack applications, add the following entry to server/middleware.json:

{
  "final:after": {
    "strong-error-handler": {
      "params": {
         "debug": false,
         "log": true
       }
    }
  }
}

In general, strong-error-handler must be the last middleware function registered.

The above configuration will log errors to the server console, but not return stack traces in HTTP responses. For details on configuration options, see below.

Response format and content type

The strong-error-handler package supports JSON, HTML and XML responses:

  • When the object is a standard Error object, it returns the string provided by the stack property in HTML/text responses.
  • When the object is a non-Error object, it returns the result of util.inspect in HTML/text responses.
  • For JSON responses, the result is an object with all enumerable properties from the object in the response.

The content type of the response depends on the request's Accepts header.

  • For Accepts header json or application/json, the response content type is JSON.
  • For Accepts header html or text/html, the response content type is HTML.
  • For Accepts header xml or text/xml, the response content type is XML.

There are plans to support other formats such as Plain-text.

Options

Option Type Default Description
debug Boolean    false If true, HTTP responses include all error properties, including sensitive data such as file paths, URLs and stack traces. See Example output below.
log Boolean true If true, all errors are printed via console.error, including an array of fields (custom error properties) that are safe to include in response messages (both 4xx and 5xx).
If false, sends only the error back in the response.
safeFields [String] [] Specifies property names on errors that are allowed to be passed through in 4xx and 5xx responses. See Safe error fields below.
defaultType String "json" Specifies the default response content type to use when the client does not provide any Accepts header.
rootProperty String or false "error" Specifies the root property name for json or xml. If the value is set to false, no wrapper will be added to the json object. The false value is ignored by XML as a root element is always required.
negotiateContentType Boolean true Negotiate the response content type via Accepts request header. When disabled, strong-error-handler will always use the default content type when producing responses. Disabling content type negotiation is useful if you want to see JSON-formatted error responses in browsers, because browsers usually prefer HTML and XML over other content types.

Customizing log format

Express

To use a different log format, add your own custom error-handling middleware then disable errorHandler.log. For example, in an Express application:

app.use(myErrorLogger());
app.use(errorHandler({log: false}));

In general, add strong-error-handler as the last middleware function, just before calling app.listen().

LoopBack

For LoopBack applications, put custom error-logging middleware in a separate file; for example, server/middleware/error-logger.js:

module.exports = function(options) {
  return function logError(err, req, res, next) {
    console.log('unhandled error' ,err);
    next(err);
  };
};

Then in server/middleware.json, specify your custom error logging function as follows:

{
  // ...
  "final:after": {
    "./middleware/error-logger": {},
    "strong-error-handler": {
      "params": {
        "log": false
      }
    }
}

The default middleware.development.json file explicitly enables logging in strong-error-handler params, so you will need to change that file too.

Safe error fields

By default, strong-error-handler will only pass through the name, message and details properties of an error. Additional error properties may be allowed through on 4xx and 5xx status code errors using the safeFields option to pass in an array of safe field names:

{
  "final:after": {
    "strong-error-handler": {
      "params": {
        "safeFields": ["errorCode"]
      }
    }
}

Using the above configuration, an error containing an errorCode property will produce the following response:

{
  "error": {
    "statusCode": 500,
    "message": "Internal Server Error",
    "errorCode": "INTERNAL_SERVER_ERROR"
  }
}

Migration from old LoopBack error handler

NOTE: This is only required for applications scaffolded with old versions of the slc loopback tool.

To migrate a LoopBack 2.x application to use strong-error-handler:

  1. In package.json dependencies, remove "errorhandler": "^x.x.x”,
  2. Install the new error handler by entering the command:
    npm install --save strong-error-handler
  3. In server/config.json, remove:
     "remoting": {
       ...
       "errorHandler": {
         "disableStackTrace": false
       }
    and replace it with:
     "remoting": {
       ...,
       "rest": {
         "handleErrors": false
       }
  4. In server/middleware.json, remove:
     "final:after": {
       "loopback#errorHandler": {}
     }
    and replace it with:
     "final:after": {
       "strong-error-handler": {}
     }
  5. Delete server/middleware.production.json.
  6. Create server/middleware.development.json containing:
     "final:after": {
       "strong-error-handler": {
         "params": {
           "debug": true,
           "log": true
         }
       }
     }
    

For more information, see Migrating apps to LoopBack 3.0.

Example

5xx error generated when debug: false :

{ error: { statusCode: 500, message: 'Internal Server Error' } }

The same error generated when debug: true :

{ error:
  { statusCode: 500,
  name: 'Error',
  message: 'a test error message',
  stack: 'Error: a test error message
  at Context.<anonymous> (User/strong-error-handler/test/handler.test.js:220:21)
  at callFnAsync (User/strong-error-handler/node_modules/mocha/lib/runnable.js:349:8)
  at Test.Runnable.run (User/strong-error-handler/node_modules/mocha/lib/runnable.js:301:7)
  at Runner.runTest (User/strong-error-handler/node_modules/mocha/lib/runner.js:422:10)
  at User/strong-error-handler/node_modules/mocha/lib/runner.js:528:12
  at next (User/strong-error-handler/node_modules/mocha/lib/runner.js:342:14)
  at User/strong-error-handler/node_modules/mocha/lib/runner.js:352:7
  at next (User/strong-error-handler/node_modules/mocha/lib/runner.js:284:14)
  at Immediate._onImmediate (User/strong-error-handler/node_modules/mocha/lib/runner.js:320:5)
  at tryOnImmediate (timers.js:543:15)
  at processImmediate [as _immediateCallback] (timers.js:523:5)' }}

4xx error generated when debug: false :

{ error:
  { statusCode: 422,
  name: 'Unprocessable Entity',
  message: 'Missing required fields',
  code: 'MISSING_REQUIRED_FIELDS' }}

strong-error-handler's People

Contributors

0candy avatar achrinza avatar amir-61 avatar aozisik avatar bajtos avatar candytangnb avatar charanrajtc avatar charlie-s avatar crandmck avatar davidcheung avatar dhmlau avatar dkrantsberg avatar gunjpan avatar kallev avatar karanssj4 avatar loay avatar raymondfeng avatar renovate-bot avatar renovate[bot] avatar shimks avatar siddhipai avatar simonhoibm avatar superkhau avatar zbarbuto avatar zmetcalf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

strong-error-handler's Issues

How can i get an single error message from loopback error body

I want that if any validation breaks, then it should break my code and return with proper error message.

I used inbuilt validation function as below:

  Customer.validatesFormatOf('mobileno', {
    with: /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/,
    message: 'Enter valid contact number'
  })

  Customer.validatesFormatOf('email', {
    with: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
    message: 'Enter valid Email'
  })

I have tried this with promise and callbacks too but result is negative.

image

I want that if my mobile no validation is true then only it will go for the email validation.

TypeError: Converting circular structure to JSON

Description

I have enabled debug error output in my LoopBack 4 application by setting RestBindings.ERROR_WRITER_OPTIONS.
After this some errors resulted in no output at all. Just 500 response with zero content.

After some digging I've found that JSON.stringify was failing on circular references and it was taking the entire node process down. Thanks to pm2 it was automatically restarting.

Here's the error stack:

TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at sendJson (/labshare/storage-api/node_modules/strong-error-handler/lib/send-json.js:9:22)
    at Function.writeErrorToResponse (/labshare/storage-api/node_modules/strong-error-handler/lib/handler.js:69:3)
    at RejectProvider.action (/labshare/storage-api/node_modules/@loopback/rest/src/providers/reject.provider.ts:41:5)
    at MySequence.reject (/labshare/storage-api/node_modules/@loopback/rest/src/providers/reject.provider.ts:27:37)
    at MySequence.handle (/labshare/storage-api/src/sequence.ts:84:12)
    at processTicksAndRejections (internal/process/next_tick.js:81:5)

I'm going to make a PR to fix this.

"Unhandled Error" for errors that have been handled properly.

See #40
This needs to be reopened and checked over.

My comment at the bottom shows that this bug is still present.

When we're writing remote methods on our models and explicitly returning an error with a statusCode and a message back up to the client, strong-error-handler should not be saying that there is an Unhandled Error, as we are clearly handling it with our methods, by the method defined in the loopback docs

Maybe if I get some free time later this week I can look into it, but for now one of the dedicated devs should really check this out.

Using the latest, loopback 3.6.0 locally and strongloop 6.0.3 globally.


Proposal from @bajtos on how to fix this issue - see #54 (comment)

As I see it, there are two parts

  1. which errors to report (4xx, 5xx, or maybe only those with no explicit statusCode property)
  2. what message to print

As for 1), we have deliberately decided to always print all errors, nothing's changing there.

As for 2), I agree that prefixing the log message with "Unhandled error" is misleading. I am proposing to change the message to Request {verb} {path} failed: {error} - see https://github.com/strongloop/strong-error-handler/blob/323cd4dfbffa3425d6d6bd00bd9ba93fbede5342/lib/logger.js

This issue is waiting for a volunteer to open a pull request and make the proposed change.

Customize XML response

Description/Steps to reproduce

Hi, is it possible to extend xml error response to include custom messages instead of the current error template?

if (data.customError) {
    content = xml([data.message]); // assuming we're using xml library
  } else {
    content = js2xmlparser.parse('error', data);
  }

in lib/send-xml.js

and the error message used is:

{
  customError: true,
  message: {
    Response: [
      {
        _attr: { service: 'RoutePushService' }
      },
      {
        Head: 'ERR'
      },
      {
        ERROR: [
          {
            _attr: { code: '4001' }
          },
          'System data error or runtime exception'
        ]
      }
    ]
  }
}

Link to reproduction sandbox

Expected result

<Response service="RoutePushService">
    <Head>ERR</Head>
    <ERROR code="4001">System data error or runtime exception</ERROR>
</Response>

Additional information

Status was present for previous strong-remoting

New release

From #73

  • After the release:
  • Update places like loopback-workspace (both package.json and templates), loopback-sanbox to use the new major version of strong-error-handler.
  • The same applies to other dependents - loopback dev-dependencies, strong-remoting dev-dependencies, etc.

404 Not found XSS (Cross Site Scripting Issue)

Hi,

I am not sure if this issue belongs to strongloop or the strongloop error handler:

You can simply generate XSS-links by using the error handler. For example:

http://your-app.com/api/containers/images/download/<img onerror=alert(1) src=a>

This will produce an HTML document containing the image and the js-code in the error-title. If debug is set to true in the middleware the code gets rendered and executed three times.

Dependency setup:

"dependencies": {
    "compression": "^1.0.3",
    "cors": "^2.5.2",
    "gm": "^1.23.0",
    "helmet": "^1.3.0",
    "loopback": "^3.0.0",
    "loopback-boot": "^2.6.5",
    "loopback-component-explorer": "^4.0.0",
    "loopback-component-storage": "^3.2.0",
    "loopback-connector-postgresql": "^3.0.0",
    "loopback-ds-timestamp-mixin": "^3.4.1",
    "node-uuid": "^1.4.8",
    "serve-favicon": "^2.0.1",
    "strong-error-handler": "^2.0.0"
  },

Defined middleware:

{
  "final:after": {
    "strong-error-handler": {
      "params": {
        "debug": true,
        "log": true
      }
    }
  }
}

Handle AssertionError as 4xx error (keep showing message even in production / debug false)

Bug or feature request

  • Bug
  • Feature request

Description of feature (or steps to reproduce if bug)

As of now, any error object that has no statusCode property will be handled as 5xx error and will not show error message in production.

This is a suggestion to show the message error for Assertion since the error thrown by assert is much used and not-so-simple to add statusCode property (can still be added using try-catch block, but to bothersome)

Link to sample repo to reproduce issue (if bug)

// debug: false
assert.ok(userId, 'userId is required');

Expected result

{
  "error": {
    "statusCode": 500,
    "name": "AssertionError",
    "message": "userId is required"
}

Actual result (if bug)

{
  "error": {
    "statusCode": 500,
    "name": "Internal Server Error"
}

Additional information (Node.js version, LoopBack version, etc)

For information purpose, I know this still can be achieved by try-catch block. But I am suggesting to handle it differently.

try {
  assert.ok(userId, 'userId is required');
} catch (error) {
  error.statusCode = 400;
  throw error;
}

Many thanks.

Allow error 2xx transmission

Hello World,

I'm writing an API that has long processing time, on some query I'd like to return a status 202 when request is pending and 201 when processing is done.

The problem I have is that strong-error-handler intercept the error < 400 and replace it by an error 500.

This is due to the line:
https://github.com/strongloop/strong-error-handler/blob/0ee193bb618f7d6a007d51f0c99e782a07d4093e/lib/data-builder.js#L69

I understand that the goal of strong-error-handler is to hide internal errors but 2xx or 3xx code are not really errors and I believe they should be shown to the user.

Could an option be added to prevent this behavior ? I would put this option in the remote method definition's json.

HTML output

Implement HTML output using hard-coded templates shipped as part of this module.

See #1 for inspiration.

Customizing HTML templates is out of scope of this issue, see #3.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore: lock file maintenance

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/codeql-analysis.yml
  • step-security/harden-runner v2.7.0@63c24ba6bd7ba022e95695ff85de572c04a18142
  • actions/checkout v4.1.4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • github/codeql-action v3.25.3@d39d31e687223d841ef683f52467bd88e9b21c14
  • github/codeql-action v3.25.3@d39d31e687223d841ef683f52467bd88e9b21c14
.github/workflows/continuous-integration.yml
  • step-security/harden-runner v2.7.0@63c24ba6bd7ba022e95695ff85de572c04a18142
  • actions/checkout v4.1.4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • actions/setup-node v4.0.2@60edb5dd545a775178f52524783378180af0d1f8
  • Yuri6037/Action-FakeTTY v1.1@1abc69c7d530815855caedcd73842bae5687c1a6
  • step-security/harden-runner v2.7.0@63c24ba6bd7ba022e95695ff85de572c04a18142
  • actions/checkout v4.1.4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • actions/setup-node v4.0.2@60edb5dd545a775178f52524783378180af0d1f8
  • step-security/harden-runner v2.7.0@63c24ba6bd7ba022e95695ff85de572c04a18142
  • actions/checkout v4.1.4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • actions/setup-node v4.0.2@60edb5dd545a775178f52524783378180af0d1f8
  • step-security/harden-runner v2.7.0@63c24ba6bd7ba022e95695ff85de572c04a18142
  • actions/checkout v4.1.4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • actions/setup-node v4.0.2@60edb5dd545a775178f52524783378180af0d1f8
.github/workflows/scorecards.yml
  • step-security/harden-runner v2.7.0@63c24ba6bd7ba022e95695ff85de572c04a18142
  • actions/checkout v4.1.4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • ossf/scorecard-action v2.3.1@0864cf19026789058feabb7e87baa5f140aac736
  • actions/upload-artifact v4.3.3@65462800fd760344b1a7b4382951275a0abb4808
  • github/codeql-action v3.25.3@d39d31e687223d841ef683f52467bd88e9b21c14
npm
package.json
  • accepts ^1.3.8
  • debug ^4.3.4
  • fast-safe-stringify ^2.1.1
  • handlebars ^4.7.8
  • http-status ^1.7.4
  • js2xmlparser ^5.0.0
  • strong-globalize ^6.0.6
  • @commitlint/cli ^19.3.0
  • @commitlint/config-conventional ^19.2.2
  • @types/express ^4.17.21
  • chai ^5.1.0
  • eslint ^8.57.0
  • eslint-config-loopback ^13.1.0
  • express ^4.19.2
  • lockfile-lint ^4.13.2
  • mocha ^10.4.0
  • supertest ^6.3.4

  • Check this box to trigger a request for Renovate to run again on this repository

Duplicate fields status and statusCode on error json payload

I am using swagger-express-middleware to validate incoming requests with loopback remote methods.
When swagger-express-middleware request-validator fails, it raises an error object with error.status being the response status code (i.e. 5xx, 4xx).

The error is then propagated through strong-error-handler which fills in status code again through

function fillStatusCode(data, err) {
  data.statusCode = err.statusCode || err.status;
  if (!data.statusCode || data.statusCode < 400)
    data.statusCode = 500;
}

the original error is then cloned in

/**
 * clone the error properties to the data objects
 * [err.name,  err.message, err.stack] are not enumerable properties
 * @param data Object to be altered
 * @param err Error Object
 */
function cloneAllProperties(data, err) {
  data.name = err.name;
  data.message = err.message;
  for (var p in err) {
    if ((p in data)) continue;
    data[p] = err[p];
  }
  // stack is appended last to ensure order is the same for response
  data.stack = err.stack;
};

This results in payload that looks like :

{
        "name": "Error",
        "message": "Missing required query parameter 'xxx'",
        "statusCode": 400,
        "status": 400
}

Additionally there are two functions namely toJSON and stack having stacktrace.

is there a way to address duplication of statuscode ?

is there a way to remove toJSON and stack from payload ?

I am on loopback 3.x version

issue with deploying to heroku

Description/Steps to reproduce

i'm running an app and get an issue:

Error: Cannot find module 'http-status'
    at Function.Module._resolveFilename (module.js:485:15)
    at Function.Module._load (module.js:437:25)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/app/node_modules/strong-error-handler/lib/data-builder.js:9:18)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/app/node_modules/strong-error-handler/lib/handler.js:11:25)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)

and everything works fine on local machine

Note i figure it out, but maybe it'll be helpful for you - it works well with node v.9.4.0 and crashing when i use node v.8.1.4

Link to reproduction sandbox

Expected result

Additional information

Use template-literal instead of EJS

Template Literal is fastest, smallest and simplest template engine, because it use JS's literal template feature,

It's 55 times faster than EJS, and it also use less CPU and RAM ressources, so it may be a good idea to use it instead of EJS 😀

XML output

At the moment, the handler can render only HTML, JSON or plain-text responses. We should implement support for XML too.

Safe fields can overwrite status code property

Safe fields introduced in #41 allow a safeFields array in options to copy properties from an error to the response payload in production mode.

If the safeFields array contains statusCode, then 500 type errors (which don't have a status code on them) will cause undefined to be copied to the response json payload, resulting in an undefined status code and an error from express.

Either the statusCode property needs to be special cased, or the fillSafeFields method needs to fallback to the existing properties in data if the given safe key is undefined in the error.

Add config option to log errors on a single line

Currently, the stack trace is printed out on separate lines. When using Docker and a log aggregator, it results in one error being split across multiple lines. I believe by adding a config option (logFormat, maybe?, with possible values of default and json), this can all be condensed to a single line.

I plan to open a PR soon, if this idea is not abhorrent to anyone.

I will focus on this function. I will add a format argument to the function signature.
https://github.com/strongloop/strong-error-handler/blob/e1a0f5954f8cded5774c86dd86aba55383a22424/lib/logger.js#L11-L22

Safefields doesn't work with "array of errors"

Description of feature (or steps to reproduce if bug)

Using loopback as an example, we can call POST with /users with an array of objects repeatedly such as below

[
  {
    "id": 1,
    "firstname": "Allen"
  },
  {
    "id": 2,
    "firstname": "Bob"
  }
]

with this middleware config:

"final:after": {
        "strong-error-handler": {
            "params": {
                "log": false,
                "safeFields": ["name", "message", "details"]
            }
        }
    }

Expected result

{
  "error": {
    "statusCode": 500,
    "name": "ArrayOfErrors",
    "message": "Failed with multiple errors, see `details` for more information.",
    "details": [
      {
        "name": "Error",
        "message": "ER_DUP_ENTRY: Duplicate entry '2' for key 'PRIMARY'",
        "code": "ER_DUP_ENTRY",
        "errno": 1062,
        "sqlState": "23000",
        "index": 0
      },
      {
        "name": "Error",
        "message": "ER_DUP_ENTRY: Duplicate entry '3' for key 'PRIMARY'",
        "code": "ER_DUP_ENTRY",
        "errno": 1062,
        "sqlState": "23000",
        "index": 0,
      }
    ]
  }
}

Actual result (if bug)

{
  "error": {
    "statusCode": 500
  }
}

Additional information (Node.js version, LoopBack version, etc)

"loopback": "^3.0.0",
"strong-error-handler": "^1.0.1"

Security Vulnerability in Strong-Globalize

Description/Steps to reproduce

npm install strong-error-handler, then npm audit

shows vulnerability in lodash in dependancy strong-globalize

Link to reproduction sandbox

N/A

Expected result

no vulnerabilities

Additional information

reported in strong-globalize strongloop/strong-globalize#139

Should update dependancy once udpated.

Migration documentation confusion

The migration from express error handler to strong-error-handler is a bit confusing. It needs more careful review, and proper steps in order to ensure proper migration.
The code snippets in the migration guide need to state when and where to be used.
What is the default option and what is a requirement and what is not.

The handleErrors: false part needs to be stated where and when to be used as well.

CC:/ @superkhau @ritch @crandmck

Support custom jsonSerializer

See strongloop/loopback#1650 (comment)

  // a custom JSON serializer function for producing JSON response bodies
  // @param sanitizedData: response data containing only safe properties
  // @param originalError: the original Error object
  jsonSerializer: function(sanitizedData, originalError) {
    if (originalError.name === 'ValidationError') {
      var details = sanitizedData.details || {};
      sanitizedData.issueCount =  details.codes && Object.keys(details.codes).length;
    }
    return sanitizedData;
  }

Extra files in node_modules

Description

When installing this package an additional file named grafana-enterprise-9.2.4.darwin-amd64.tar.gz is seen under node_modules/strong-error-handler . But this file is not present in the source code

Steps to reproduce

  • Create a new npm project: npm init

  • npm i strong-error-handler

Expected result

No additional files should be seen in node_modules/strong-error-handler apart from files in source code

Actual result

Additional tar file grafana-enterprise-9.2.4.darwin-amd64.tar.gz is seen

Additional information

linux x64 18.12.1

debug false not working in middleware

Bug or feature request

  • Bug
  • Feature request

Description of feature (or steps to reproduce if bug)

Link to sample repo to reproduce issue (if bug)

Expected result

Actual result (if bug)

Additional information (Node.js version, LoopBack version, etc)

Customize HTML templates

Customize html templates in strong-error-handler, see strongloop/loopback#1650 (comment) for details.

Configuration options:

// map of templates to use for rendering responses
views: {
  // the default view
  default: path.resolve(__dirname, 'views/error-default.jade'),
  404: path.resolve(__dirname, 'views/error-not-found.jade'),
  // etc.
},

// map of static files to send as a response
files: {
  // default: path.resolve(__dirname, 'public/error.html'),
  401: path.resolve(__dirname, 'views/error-unauthorized.html'),
  // etc.
},

Requires #5

Custom JSON response content

Hello.

I'm required to return error responses in the below format

{
  "code": "BAD_ARGUMENTS"
  ...
}

But currently send-json.js restricts us to the below format

{
  "error": {
    "code": "BAD_ARGUMENTS"
    ...
  }
}

Is there a solution to this that does not involve me maintaining multiple forks?

Thanks

"Unhandled error" logged for errors that have been handled correctly (e.g. a validation error)

Description of feature (or steps to reproduce if bug)

With the introduction of strong-error-handler in 3.0, we're seeing validation and access errors logging an "Unhandled error" to console. We consider the error to have been handled correctly, and so would like an easy way to suppress these messages for certain error codes (potentially all 4xx). I think this should be the default behavior - and at least easy to configure.

You can see the "unhandled error" being recorded here: https://github.com/strongloop/strong-error-handler/blob/master/lib/logger.js

You can find some extra context in this Google Groups discussion)

Link to sample repo to reproduce issue (if bug)

Instructions to replicate provided by Buck Bito in the Google Groups discussion

The quick test to reproduce with 2.38.0 or 3.2.1:

  1. Use lb to create a fresh "api-server (A LoopBack API server with local User auth)"
  2. cd into the project dir
  3. node . (to start app)
  4. Open API explorer in browser
  5. Go to User > GET /Users and "Try it out!"

Expected result

Familiar error response body in the Explorer.

Actual result (if bug)

Familiar error response body in the Explorer and Unhandled Error in the console.

Additional information (Node.js version, LoopBack version, etc)

Incorrect comment for negotiateContentProducer

Description of feature (or steps to reproduce if bug)

negotiateContentProducer in lib/content-negotiation.js has its arguments in the incorrect order. It lists them in the comments as req, options, logWarning but in the signature as req, logWarning, options.

[strong-error-handler] Documentation impact

Added https://docs.strongloop.com/display/APIC/Using+strong-error-handler that incorporates the README content.

From @loay:

  • The express error-handler was basically meant for development modes and we had to add few properties to disable stack traces in our Loopback modules in order to prevent leaking sensitive information. Strong-error-handler works for both environments as written in the description and can protect the leak of sensitive info in production.
  • It is already in Loopback scafolldiing and gets generated with new loopback apps.
  • I fail to see the relation with the debug strings, which is meant for debugging and not error handling.
    • Yes, but strong-error-handler has a "debug mode", and first sentence of README says "...for use in development (debug)..." so it begs the question. I think the key distinction that I was reaching for is that strong-error-handler only affects HTTP response content and return codes, NOT anything written to the console (by default). In contrast the LB debug strings only affect info printed to the console. ... That may be obvious to you (us), but not necc. to user immediately. Please confirm.

From @bajtos:
I think there should be a brief description of why someone should use this module.
See the information in strongloop/loopback#1650
It would be great to copy useful bits from that issue into the official LoopBack docs, possibly to strong-error-handler's README too.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.