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)
console.log(normalizedError.name)
}
console.log(normalizeException('message'))
console.log(normalizeException({ name: 'TypeError', message: 'message' }))
Invalid stack
const error = new TypeError('message')
console.log(error.stack)
error.message += ' otherMessage'
console.log(error.stack)
const normalizedError = normalizeException(error)
console.log(normalizedError.stack)
Invalid properties
const error = new Error('message', { cause: 'innerError' })
console.log(error.cause instanceof Error)
const normalizedError = normalizeException(error)
console.log(normalizedError.cause instanceof Error)
console.log(normalizedError.cause)
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!