Skip to content

Commit

Permalink
Fix error.name
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Jun 5, 2022
1 parent 5a98f10 commit 961b88b
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions src/error/create.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,34 @@
// Create an error type with a specific `name`.
// The constructor allows setting either `error.cause` or any properties:
// `new ErrorType('message', { anyProp: true })`
export const createErrorType = function (name) {
return class extends Error {
constructor(message, { cause, ...props } = {}) {
super(message, { cause })
export const createErrorType = function (errorName) {
const ErrorType = class extends Error {
// eslint-disable-next-line no-unused-vars
constructor(message, { cause, name, ...props } = {}) {
const errorOpts = cause === undefined ? {} : { cause }
super(message, errorOpts)
// eslint-disable-next-line fp/no-this, fp/no-mutating-assign
Object.assign(this, props)
// eslint-disable-next-line fp/no-this, fp/no-mutation
this.name = name
}
}
setErrorName(ErrorType, errorName)
return ErrorType
}

// To mimic native error types and to print correctly with `util.inspect()`:
// - `error.name` should be assigned on the prototype, not on the instance
// - the constructor `name` must be set too
const setErrorName = function (ErrorType, name) {
setNonEnumProp(ErrorType, 'name', name)
setNonEnumProp(ErrorType.prototype, 'name', name)
}

const setNonEnumProp = function (object, propName, value) {
// eslint-disable-next-line fp/no-mutating-methods
Object.defineProperty(object, propName, {
value,
writable: false,
enumerable: false,
configurable: true,
})
}

0 comments on commit 961b88b

Please sign in to comment.