Skip to content

Commit

Permalink
Add onCreate()
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Jun 5, 2022
1 parent 408d890 commit 3df1ab2
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/error/create.js
Original file line number Diff line number Diff line change
@@ -1,20 +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 (errorName) {
export const createErrorType = function (
errorName,
onCreate = defaultOnCreate,
) {
const ErrorType = class extends Error {
// eslint-disable-next-line no-unused-vars
constructor(message, { cause, name, ...props } = {}) {
constructor(message, { cause, name, ...opts } = {}) {
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
onCreate(this, opts)
}
}
setErrorName(ErrorType, errorName)
return ErrorType
}

// `onCreate()` allows custom logic at initialization time.
// The construction arguments are passed.
// - They can be validated, normalized, etc.
// - No third argument is passed. This enforces calling named parameters
// `new ErrorType('message', opts)` instead of positional ones, which is
// cleaner.
const defaultOnCreate = function (error, opts) {
// eslint-disable-next-line fp/no-mutating-assign
Object.assign(error, opts)
}

// 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
Expand Down

0 comments on commit 3df1ab2

Please sign in to comment.