Skip to content

Commit

Permalink
Validate error.name
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Jun 5, 2022
1 parent 3df1ab2 commit 023b4c8
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/error/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const createErrorType = function (
errorName,
onCreate = defaultOnCreate,
) {
validateErrorName(errorName)
const ErrorType = class extends Error {
// eslint-disable-next-line no-unused-vars
constructor(message, { cause, name, ...opts } = {}) {
Expand All @@ -18,6 +19,36 @@ export const createErrorType = function (
return ErrorType
}

// Validate `error.name` looks like `ExampleError`.
const validateErrorName = function (errorName) {
if (typeof errorName !== 'string') {
throw new TypeError(`Error name must be a string: ${errorName}`)
}

if (!errorName.endsWith(ERROR_NAME_END) || errorName === ERROR_NAME_END) {
throw new Error(
`Error name "${errorName}" must end with "${ERROR_NAME_END}"`,
)
}

validateErrorNamePattern(errorName)
}

const validateErrorNamePattern = function (errorName) {
if (errorName[0] !== errorName.toUpperCase()[0]) {
throw new Error(
`Error name "${errorName}" must start with an uppercase letter.`,
)
}

if (!ERROR_NAME_REGEXP.test(errorName)) {
throw new Error(`Error name "${errorName}" must only contain letters.`)
}
}

const ERROR_NAME_END = 'Error'
const ERROR_NAME_REGEXP = /[A-Z][a-zA-Z]*Error$/u

// `onCreate()` allows custom logic at initialization time.
// The construction arguments are passed.
// - They can be validated, normalized, etc.
Expand Down

0 comments on commit 023b4c8

Please sign in to comment.