-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
26 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}) | ||
} |