JSPM

  • Created
  • Published
  • Downloads 127813
  • Score
    100M100P100Q162605F
  • License Apache-2.0

Normalize exceptions/errors

Package Exports

  • normalize-exception

Readme

Codecov Build Node Twitter Medium

Normalize exceptions/errors.

In JavaScript, one can throw any value including strings, objects (like { message: "..." }) or even undefined. This normalizes any exception to an Error instance.

It also fixes any missing or invalid error properties: name, message, stack, cause, errors.

Examples

Invalid types

import normalizeException from 'normalize-exception'

try {
  throw null
} catch (error) {
  const normalizedError = normalizeException(error)
  console.log(normalizedError) // Error: null
  // Without `normalizeException()`, this would throw
  console.log(normalizedError.name)
}
console.log(normalizeException('message')) // Error: message
console.log(normalizeException({ name: 'TypeError', message: 'message' })) // TypeError: message

Invalid stack

const error = new TypeError('message')
console.log(error.stack) // TypeError: message

// `error.stack` is cached, so it does not update
error.message += ' otherMessage'
console.log(error.stack) // TypeError: message

const normalizedError = normalizeException(error)
console.log(normalizedError.stack) // TypeError: message otherMessage

Invalid properties

const error = new Error('message', { cause: 'innerError' })
console.log(error.cause instanceof Error) // false

const normalizedError = normalizeException(error)
console.log(normalizedError.cause instanceof Error) // true
console.log(normalizedError.cause) // Error: innerError

Install

npm install normalize-exception

This package is an ES module and must be loaded using an import or import() statement, not require().

API

normalizeException(error)

error any
Return value: Error

normalizeException() never throws.

If error is an Error instance, it is returned. Any missing or invalid error property is directly modified.

If it is not an Error instance, a new one is created and returned.

Support

For any question, don't hesitate to submit an issue on GitHub.

Everyone is welcome regardless of personal background. We enforce a Code of conduct in order to promote a positive and inclusive environment.

Contributing

This project was made with ❤️. The simplest way to give back is by starring and sharing it online.

If the documentation is unclear or has a typo, please click on the page's Edit button (pencil icon) and suggest a correction.

If you would like to help us fix a bug or add a new feature, please check our guidelines. Pull requests are welcome!