liquid-labs / standard-error-set

undefined
Apache License 2.0
0 stars 1 forks source link

standard-error-set

coverage: 100% Unit tests

A collection of common/standard error types to flesh out JavaScript's rather anemic baseline.

This project is currently in beta. There are no known issues and we are using it in several of our own projects without issue. There's at least one update we want to make before promoting to general release.

Features

Table of contents

Install

npm i standard-error-set

Usage and use cases

Create semantically precise errors for better error handling:

import { ArgumentTypeError } from '@liquid-labs/common-error' // ESM
// const { ArgumentTypeError } = require('@liquid-labs/common-error') // CJS

const parseArgs = ({ arg = process.argv }) => {
  const typeofArg = typeof arg
  if (typeofArg !== 'string') {
    throw new ArgumentTypeError({ argumentName : 'arg', argumentType : 'string', receivedType : typeofArg })
  }
  ...
  return options
}

Quickly test and re-throw errors:

try {
  parseArgs()
} catch (e) {
  // let non-ArgumentInvalidErrors bubble up
  rethrowIf(e, { notInstanceOf: [ArgumentInvalidError] })
  // handle user input/argument errors:
  process.stdout.write(`ERROR: ${e.message}\n`)
}

Wrap many standard errors in semantically strong error types:

import { wrapError } from '@liquid-labs/common-error' // ESM
// const { wrapError } = require('@liquid-labs/common-error') // CJS

try {
  await fetch('www.foo.com')
} catch (e) {
  throw wrapError(e)[0] // throws type specific based on e.code
}

API

Common parameters

The following option parameters are accepted by all CommonError error constructors. We document them here to save space and avoid repeating them for each error class. They are all optional.

Common instance fields

All option parameters passed to any CommonError (or sub-class) constructor are captured as instance fields. E.g.:

const error = new ArgumentInvalidError({ argumentName: 'foo' })
// sets: error.argumentName = 'foo'

All CommonError and sub-class instances will set message, status, and statusName. statusName is always determined by the status (which is either explicitly set or determined by the error type) and the current status to name mapping.

Message construction

All CommonError and CommonError sub-classes support parameterized message construction. That is, they will generate a standard message based on class specific parameters unless message is explicitly specified on the constructor options. Refer to the class documentation for parameter definition and message examples.

Error code hoisting

When the cause constructor option defines a code instance field, the code value is hoisted to the new CommonError unless overridden by either the code or noHoistCode option. E.g.:

const cause = new Error()
cause.code = 'ENOENT'
const hoistError = new CommonError({ cause }) // hoistError.code === 'ENOENT'
const codeError = new CommonError({ cause, code: 'EISDIR' }) // codeError.code === 'EISDIR'
const noHoistError = new CommonError({ cause, noHoistCode: true }) // noHoistError.code === undefined

API reference

API generated with dmd-readme-api.

ArgumentInvalidError source code global class index

Indicates an invalid argument which by default is interpreted as a user supplied argument/input.

Setting and interpreting InvalidArgumentError status

By convention, you can disambiguate user supplied arguments vs internally supplied (e.g., from code or a service) by setting and looking at the error status. A status of 400 indicates bad user input, while a status of 500 would indicate an internal problem. This is important in error handling since the message to a user is different if they can correct the input and retry vs. a problem which is internal and the user has no control over.

If your system does not deal with user input or otherwise wishes to default InvalidArgumentError instances to a different status code, use mapErrorToHttpStatus. Just note that this will change the default status code for all ArgumentInvalidError instances, even those created in other packages/libraries.

Alternate error classes

Consider whether any of the following errors might be more precise or better suited:

Category: Argument errors

new ArgumentInvalidError([options], defaults)

The ArgumentInvalidError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.endpointType] string 'command' The type of "endpoint" consuming or defining the argument. E.g., 'URL', 'configuration settings', 'function', etc.
[options.packageName] string | undefined The package name. E.g., the Javascript package or module.
[options.endpointName] string | undefined The endpoint name. For example, the command name, the URL endpoint, or the function name.
[options.argumentName] string | undefined The argument name.
[options.argumentType] string | undefined The argument type.
[options.argumentValue] * The argument value. Because this is value is ignored when undefined, consider using the string 'undefined' if it's important to display the value.
[options.issue] string 'is invalid' The issue with the argument.

Example:

new ArgumentInvalidError() // "Function argument is invalid."
"Function 'my-package#foo()' argument  is invalid."
new ArgumentInvalidError({ packageName: 'my-package', endpointName: 'foo'})
"Function argument 'bar' cannot be parsed."
new ArgumentInvalidError({ argumentName: 'bar', issue: 'cannot be parsed'})
"Function 'my-package#foo()' argument 'bar' with value '100' is invalid."
new ArgumentInvalidError({ packageName: 'my-package', endpointName: 'foo', argumentName: 'bar', argumentValue: 100 })
// v "Function argument 'bar' is invalid."
new ArgumentInvalidError({ endpointType: 'function', argumentName: 'bar' })

ArgumentMissingError source code global class index

An ArgumentInvalidError sub-type indicating a argument is missing or empty which by default is interpreted as a user supplied argument/input. See discussion on setting and interpreting InvalidArgumentError status for more detail.

If using the class parameters to construct the error message, where issue is not set and argumentValue is specified, ArgumentMissingError determines the default issue based on the value of argumentValue. The logic recognizes null, undefined, '' (the empty string), {} (empty object), and [] ( empty array). E.g., argumentValue = null yields issue issue = "is 'null'".

If your code has a different concept of what constitutes an "empty" argument, you'll need to specify the issue parameter in the constructor options. E.g., { issue: "field 'foo' is not defined" }.

Since the argument value is implied in the issue and stating the value would be redundant, when the issue is automatically customized and ignoreForMessage is not defined, the logic will set ignoreForMessage = ['argumentValue'] or merge ['argumentValue'] with any globally configured ignoreForMessage option. To suppress this behavior, pass in an explicit ignoreForMessage (an empty array and undefined are equivalent). If you want to be sure and maintain the global settings, set ignoreForMessage to commonErrorSettings('ignoreForMessage').

Consider whether any of the following errors might be more precise or better suited:

Category: Argument errors

new ArgumentMissingError([options], defaults)

The ArgumentMissingError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.endpointType] string 'command' The type of "endpoint" consuming the argument.
[options.packageName] string | undefined The package name.
[options.endpointName] string | undefined The endpoint name.
[options.argumentName] string | undefined The argument name.
[options.argumentType] string | undefined The argument type.
[options.argumentValue] * The argument value. Because this is value is ignored when undefined, consider using the string 'undefined' if it's important to display the value.
[options.issue] string ('is missing or empty'|<other>) The issue with the argument. The default value is determined by the value (or absence) of argumentValue. Refer to discussion of customized issue logic for details.

Example:

new ArgumentInvalidError() // "Function argument is missing or empty."
//  "Function 'my-package#foo()' argument is missing or empty."
new ArgumentInvalidError({ packageName: 'my-package', endpointName: 'foo'})
//  "Function 'my-package#foo()' argument with value 'undefined' is missing or empty."
new ArgumentInvalidError({ packageName: 'my-package', endpointName: 'foo', argumentName: 'bar', argumentValue: 'undefined' })
// v "Function argument 'bar' is missing or empty."
new ArgumentInvalidError({ endpointType: 'function', argumentName: 'bar' })

ArgumentOutOfRangeError source code global class index

An ArgumentInvalidError sub-type indicating a (typically user supplied) argument is of the correct time, but outside the acceptable range. Refer to ArgumentInvalidError for handling of internal argument errors.

The [includeForMessage](#common-constructor-options-ignore-for-message] option for this function recognizes the special 'boundary' value. If included, then the entire boundary description (based on the max, min, etc. options) will be suppressed. And while it is possible to exclude the individual boundary parameters, excluding a subset would be strange.

Consider whether any of the following errors might be more precise or better suited:

Category: Argument errors

new ArgumentOutOfRangeError([options], defaults)

The ArgumentOutOfRangeError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.endpointType] string 'command' The type of "endpoint" consuming the argument.
[options.packageName] string | undefined The package name.
[options.endpointName] string | undefined The endpoint name.
[options.argumentName] string | undefined The argument name.
[options.argumentType] string | undefined The argument type.
[options.argumentValue] * The argument value. Because this is value is ignored when undefined, consider using the string 'undefined' if it's important to display the value.
[options.max] string | number | undefined The maximum value; the value must be less than or equal to this.
[options.maxBoundary] string | number | undefined The upper value boundary; the value must be less than this. This value will be ignored if max is set.
[options.min] string | number | undefined The minimum; the value must be greater than or equal to this.
[options.minBoundary] string | number | undefined The lower value boundary; the value must be greater than this. This value will be ignored if min is set.
[options.issue] string 'is out of range' The issue with the argument.

Example:

new ArgumentOutOfRangeError() // "Function argument is out of range."
//  "Function 'foo()' argument is out of range. Value must be greater than or equal to 24."
new ArgumentOutOfRangeError({ endpointName: 'foo', argumentValue: 12, min: 24 })
//  "Function argument 'bar' with value '100' is out of range. Value must be greater than or equal to 'C' and less than 'D'."
new ArgumentInvalidError({ argumentName: 'bar', argumentValue: 'Bob', min: 'C', maxBoundary: 'D' })
// v "Function argument 'bar' is out of range."
new ArgumentInvalidError({ endpointType: 'function', argumentName: 'bar' })

ArgumentTypeError source code global class index

An ArgumentInvalidError sub-type indicating a (typically user supplied) argument is not the correct type. Refer to ArgumentInvalidError for handling of internal argument errors.

Consider whether any of the following errors might be more precise or better suited:

Category: Argument errors

new ArgumentTypeError([options], defaults)

The ArgumentTypeError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.endpointType] string 'command' The type of "endpoint" consuming the argument.
[options.packageName] string | undefined The package name.
[options.endpointName] string | undefined The endpoint name.
[options.argumentName] string | undefined The argument name.
[options.argumentType] string | undefined The (expected) argument type.
[options.receivedType] string | undefined The actual type of the argument. If this is not set, but argumentValue is provided then unless receivedType is ignored, the typeof argumentValue will be used as the received type.
[options.argumentValue] * The value of the argument; though we recommend to leave this undefined. The value is generally not important since the type is incorrect.
[options.issue] string 'is wrong type' The issue with the argument.

Example:

new ArgumentInvalidError() // "Function argument is wrong type."
//  "Function 'my-package#foo()' argument is wrong type."
new ArgumentInvalidError({ packageName: 'my-package', endpointName: 'foo'})
//  "Function 'my-package#foo()' argument with value 'undefined' is wrong type."
new ArgumentInvalidError({ packageName: 'my-package', endpointName: 'foo', argumentName: 'bar', argumentValue: 'undefined' })
// v "Function argument 'bar' is wrong type."
new ArgumentInvalidError({ endpointType: 'function', argumentName: 'bar' })

AuthenticationRequiredError source code global class index

An AuthError sub-class indicating that an operation requires an authenticated user and the current us not authenticated.

Category: Auth errors

new AuthenticationRequiredError([options], defaults)

AuthenticationRequiredError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string 'action' A short description of the action.
[options.target] string | undefined A short description of the action target.
[options.issue] string 'requires authorization' The auth issue.

Example:

new AuthenticationRequiredError() // "Action requires authentication."
new AuthenticationRequiredError({ action : 'endpoint access' }) // "Endpoint access requires authentication."
// v "Updating the customer database requires authentication."
new AuthenticationRequiredError({ action : 'updating', target : 'customer database' })

AuthError source code global class index

A generic error indicating a problem with user authentication or authorization. AuthError should generally not be used directly, but instead is intended as a base class for auth related errors allowing consumers to check for auth related errors broadly (e.g., instanceof AuthError). Generally, will want to use one of the following:

Category: Auth errors

new AuthError([options], defaults)

AuthError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string 'action' A short description of the action.
[options.target] string | undefined The name or short description of the target.
[options.issue] string 'is not authorized' The auth issue.

Example:

new AuthError() // "Action is not authorized."
new AuthError({ action : 'dancing' }) // "Dancing is not authorized."
new AuthError({ issue : 'is not permitted' }) // Action is not permitted.

AuthorizationConditionsNotMetError source code global class index

An AuthError indicating that the user is authorized to perform some action under some circumstances, but additional conditions must be met. The blocking or necessary conditions should be described if possible.

Consider whether any of the following errors might be more precise or better suited:

Category: Auth errors

new AuthorizationConditionsNotMetError([options], defaults)

Constructor for the AuthorizationConditionsNotMetError.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string | undefined A description of the action being taken. This should identify the target resource/entity where appropriate. E.g., 'accessing the database' or 'updating customer data'.
[options.hint] string | undefined A description of what the user might do to remedy the situation. This should be a complete sentence. E.g., 'You may contact customer service and request a quota increase.', or 'Try again in a few minutes.'
[options.issue] string 'current conditions prevent this action' A description of the problem. E.g., 'the user is over request quota', or 'this operation is only allowed between 0900 and 1700'.

Example:

new AuthorizationConditionsNotMet() // "While generally authorized, current conditions prevent this action."
// v "While generally authorized to access customer data, current conditions prevent this action."
new AuthorizationConditionsNotMet({ action: 'access customer data' })
// v "While generally authorized, user is over rate quota."
new AuthorizationConditionsNotMet({ issue: 'user is over rate quota' })
// v "While generally authorized to access customer data, user is over rate quota."
new AuthorizationConditionsNotMet({ action: 'access customer data', issue: 'user is over rate quota' })
// v "While generally authorized, current conditions prevent this action. Try again in a few minutes."
new AuthorizationConditionsNotMet({ hint: 'Try again in a few minutes.' })

BadCredentialsError source code global class index

An AuthError sub-class indicating the provided credentials are invalid.

Category: Auth errors

new BadCredentialsError([options], defaults)

BadCredentialsError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string 'authentication' A short description of the action.
[options.issue] string | undefined Additional specifics regarding the issue.
[options.method] string | undefined The authentication method. E.g., 'password', 'SSL cert', etc.

Example:

new BadCredentialsError() // "Authentication failed."
new BadCredentialsError({ method: 'password' }) // "Authentication of password failed."
new BadCredentialsError({ action : 'decoding', method: 'SSL cert' }) // "Decoding of SSL cert failed."
new BadCredentialsError({ issue: 'certificate not signed' }) // "Authentication failed; certificate not signed."

NoAccessDirectoryError source code global class index

An NoAccessError indicating a user lacks the rights to access a particular directory. Note, in high security systems, it is often desirable to tell the user a resource was 'not found', even when the problem is really an access issue, use and see maskNoAccessErrors to deal with this situation.

Consider whether any of the following errors might be more precise or better suited:

Category: Auth errors

new NoAccessDirectoryError([options], defaults)

NoAccessDirectoryError constructor. Refer to DirectoryNotFoundError for additional examples of constructed messages when a 404 status is set or mapped to this error type.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.dirPath] string | undefined The directory (not including the file itself) where the file is located.
[options.resource] string | undefined Should usually be left undefined. If set, then the value will override dirPath and be used to generate the standard message if message option not set.}

Example:

new NoAccessDirectoryError() // "Access to directory is denied."
new NoAccessDirectoryError() // when access errors mapped to 404: "Directory not found."
new NoAccessDirectoryError({ dirPath = '/foo' }) // "Access to director '/foo' is denied"

NoAccessError source code global class index

An AuthError indicating a user lacks the rights to access a particular resource. This error is most appropriate when trying to read or write something. If the user is attempting to perform an operation, consider the OperationNotPermittedError. Note, in high security systems, it is often desirable to tell the user a resource was 'not found', even when the problem is really an access issue, use and see maskNoAccessErrors to deal with this situation.

Consider whether any of the following errors might be more precise or better suited:

Category: Auth errors

new NoAccessError([options], defaults)

NoAccessError constructor. Refer to NotFoundError for additional examples of constructed messages when a 404 status is set or mapped to this error type.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.resource] string | undefined A description of the resource attempting to be accessed.
[options.status] number (404 | 409) The HTTP status of the error. Should generally be left undefined so as to be automatically determined according to [@link mapErrorToHttpStatus configured error mapping].

Example:

new NoAccessError() // "Access to resource is denied."
new NoAccessError() // when mapped to 404 status: "Resource is not found."
new NoAccessError({ resource : 'terminal connection' }) // Access to terminal connection is denied.

NoAccessFileError source code global class index

An NoAccessError indicating a user lacks the rights to access a particular file. Note, in high security systems, it is often desirable to tell the user a resource was 'not found', even when the problem is really an access issue, use and see maskNoAccessErrors to deal with this situation.

Consider whether any of the following errors might be more precise or better suited:

Category: Auth errors

new NoAccessFileError([options], defaults)

NoAccessFileError constructor. Refer to FileNotFoundError for additional examples of constructed messages when a 404 status is set or mapped to this error type.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.dirPath] string | undefined The directory (not including the file itself) where the file is located. If defined, and the resource option is undefined, then dirPath is combined with fileName, if present, to define the resource. This option cannot be suppressed directly, but the resource can be.
[options.fileName] string | undefined The name of the file itself. May be a full path (in which case dirPath should be left undefined) or just the file name. If defined, and the resource option is undefined, then fileName is combined with dirPath, if present, to define the resource. This option cannot be suppressed directly, but the resource can be.
[options.resource] string | undefined Should usually be left undefined. If set, then the value will override fileName and dirPath and be used to generate the standard message if message option not set.

Example:

new NoAccessFileError() // "Access to file is denied."
new NoAccessFileError() // when status is 404: "File not found."
new NoAccessFileError({ fileName: 'bar' }) // Access to file 'bar' is denied.
new NoAccessFileError({ dirPath: '/foo', fileName: 'bar' }) // Access to file '/foo/bar' is denied.
new NoAccessFileError({ dirPath: '/foo' }) // Access to file in directory '/foo' is denied.

OperationNotPermittedError source code global class index

An AuthError indicating the user lacks authorization to perform some operation. This is most appropriate when the user is trying to do something. If the user is attempting to "access" a resource, the NoAccessError or it's children may be better suited. Consider whether any of the following errors might be more precise or better suited:

Category: Auth errors

new OperationNotPermittedError([options], defaults)

OperationNotPermittedError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string 'action' A short description of the action.
[options.target] string | undefined The name or short description of the target.
[options.issue] string 'is not permitted' The auth issue.

Example:

new OperationNotPermittedError() // "Action is not permitted."
new OperationNotPermittedError({ action = 'database update' }) // "Database update is not permitted."
// v "Accessing the customer database is not permitted."
new OperationNotPermittedError({ target = 'customer database' })
// v "Updating the customer database is not permitted."
new OperationNotPermittedError({ action = 'updating', target = 'customer database '})
new OperationNotPermittedError({ issue = 'is not authorized' }) // Action is not authorized.

ConstraintViolationError source code global class index

Indicates the requested operation is well formed and the data otherwise correct, but it violates a data constraint. ConstraintViolationError is distinguished from ArgumentInvalidError in that argument errors are evaluated at the function level, while constraint violations result from database constraints. Refer to DatabaseError for remote vs local database errors.

Category: Database errors

new ConstraintViolationError([options], defaults)

ConstraintViolationError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.constraintType] string 'constraint' The constraint type.
[options.entityType] string | undefined The "type" of entity. E.g., 'user'.
[options.fieldAndValues] Array.<string> | Array.<Array.string> [] An array of either field names and/or arrays of field name + field value. You may mix and match, e.g., ['field1', ['field2', 'value2'].
[options.isLocal] boolean false Indicates whether the error arises from a remote database or not.

Example:

new ConstraintViolationError() // "Constraint violated."
new ConstraintViolationError({ constraintType: 'foreign key' }) // "Foreign key constraint violated."
new ConstraintViolationError({ entityType : 'user' }) // "Constraint on entity type 'user' violated."
// v "Enumeration constraint on fields <email> on entity type 'user' violated."
new ConstraintViolationError({ constraintType : 'enumeration', entityType : 'user', fieldAndValues : ['email'] })
// v "Constraint on fields <email(john@foo.com)> on entity type 'user' violated."
new ConstraintViolationError({ entityType : 'user', fieldAndValues : [['email', 'john@foo.com']] })

DatabaseError source code global class index

Indicates a problem within a database system implementation.

In general, these errors arise from an external service. However, since they can also occur within a database implementation itself, we don't extend ExternalServiceError, but rather include an 'isLocal' setting, which defaults to the common case of false.

Consider whether any of the following errors might be more precise or better suited:

Category: Database errors

new DatabaseError([options], defaults)

DatabaseError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string | undefined A description of the action being taken. E.g., 'closing', 'creating', etc.
[options.errorType] string 'an error' A description of the error type.
[options.issue] string | undefined Describes the specific issue.
[options.isLocal] boolean false Indicates whether the error arises from a remote database or not.
[options.target] string 'target' The name or description of the target resource.

Example:

new DatabaseError() // "There an error in the database."
new DatabaseError({ action : 'syncing' }) // "There was an error syncing the database."
new DatabaseError({ target : 'customer database' }) // "There was an error in the customer database."
// v "There was an error creating the customer database."
new DatabaseError({ action: 'creating', target : 'customer database' })
// v "There was an error in the customer database; virtual socket closed."
new DatabaseError({ issue : 'virtual socket closed', target : 'customer database' })

RollbackError source code global class index

An DatabaseError sub-type relating to a failed rollback within a database. Use RollbackError on the client side to indicate a failed rollback in an external data service. Refer to DatabaseError for remote vs local database errors.

Consider whether any of the following errors might be more precise or better suited:

Category: Database errors

new RollbackError([options], defaults)

RollbackError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string | undefined A description of the action being taken. E.g., 'closing', 'creating', etc.
[options.errorType] string 'a rollback error' A description of the error type.
[options.issue] string | undefined Describes the specific issue.
[options.target] string 'database' The name or description of the target resource.
[options.isLocal] boolean false Indicates whether the error arises from a remote database or not.

Example:

new RollbackError() // "There a rollback error in the database."
new RollbackError({ action : 'updating' }) // "There was a rollback error updating the database."
new RollbackError({ target : 'customer database' }) // "There was a rollback error in the customer database."
// v "There was a rollback error updating the customer database."
new RollbackError({ action: 'updating', target : 'customer database' })
// v "There was a rollback error in the customer database; virtual socket closed."
new RollbackError({ issue : 'virtual socket closed', target : 'customer database' })

TransactionError source code global class index

An DatabaseError indicating a problem creating or otherwise involving a transaction within a database system itself. Use TransactionError for transaction errors related to transactions in an external database service. Refer to DatabaseError for remote vs local database errors.

Consider whether any of the following errors might be more precise or better suited:

Category: Database errors

new TransactionError([options], defaults)

TransactionError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string | undefined A description of the action being taken. E.g., 'closing', 'creating', etc.
[options.errorType] string 'an error' A description of the error type.
[options.issue] string | undefined Describes the specific issue.
[options.target] string 'database' The name or description of the target resource.
[options.isLocal] boolean false Indicates whether the error arises from a remote database or not.

Example:

new TransactionError() // "There was a transaction error in the database."
new TransactionError({ action : 'closing' }) // "There was an error closing the transaction."
// v "There was a transaction error on the customer database."
new TransactionError({ target : 'customer database' })
// v "There was an error closing the transaction on the customer database."
new TransactionError({ action: 'creating', target : 'customer database' })
// v "There was a transaction error on the customer database; virtual socket closed."
new TransactionError({ issue : 'virtual socket closed', target : 'customer database' })

UniqueConstraintViolationError source code global class index

A ConstraintViolationError sub-type indicating violation of a unique constraint, such as login ID. Refer to DatabaseError for remote vs local database errors.

Category: Database errors

new UniqueConstraintViolationError([options], defaults)

UniqueConstraintViolationError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.constraintType] string 'unique constraint' The constraint type.
[options.entityType] string | undefined The "type" of entity (e.g., 'user'; optional).
[options.fieldAndValues] Array.<string> | Array.<Array.string> [] An array of either field names and/or arrays of field name + field value (optional). You may mix and match, e.g., ['field1', ['field2', 'value2'].
[options.isLocal] boolean false Indicates whether the error arises from a remote database or not.

Example:

new UniqueConstraintViolationError() // "Unique constraint violated."
new UniqueConstraintViolationError({ entityType : 'user' }) // "Unique constraint on entity type 'user' violated."
// v "Unique constraint on fields <email>."
new UniqueConstraintViolationError({ entityType : 'user', fieldAndValues : ['email'] })
// v "Unique constraint on fields <email(john@foo.com)> on entity type 'user' violated."
new UniqueConstraintViolationError({ entityType : 'user', fieldAndValues : [['email', 'john@foo.com']] })

ConnectionError source code global class index

An ExternalServiceError sub-type indicating a problem with a connection, including making a connection. The standard instance message is determined by the code instance field, which indicates the specific nature of the connection error. Recall that due to error code hoisting, the code of the cause Error will set the ConnectionError code (unless the constructor options code is set or noHoistCode is true) and the hoisted code will determine the standard message (unless the message option is defined).

Consider using TimeoutError when the problem is specifically a connection timeout.

Category: External service errors

new ConnectionError([options], defaults)

Constructor for the ConnectionError class.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.issue] string variaus Typically left undefined and determined automatically according to the error code. Describes the specific issue.
[options.target] string | undefined The name or description of the connection target.

Example:

new ConnectionError() // "Connection has experienced an unknown error."
// v "Connection to host 'foo.com' has experienced an unknown error."
new ConnectionError({ target: "to host 'foo.com'" })
// v "Connection to host 'foo.com' is blocked by system firewall."
new ConnectionError({ target: "to host 'foo.com'", issue: 'is blocked by system firewall' })
new ConnectionError({ code: 'ECONNRESET' }) // "Connection has been reset."
const cause = new Error()
const cause.code = 'ECONNRESET'
const connError = new ConnectionError({ cause }) // also "Connection has been reset."

ExternalServiceError source code global class index

Indicates an error related to an external service. Not that database related errors have their own distinct class which is used for both local and remote database errors.

Consider whether any of the following errors might be more precise or better suited:

Category: External service errors

new ExternalServiceError([options], defaults)

ExternalServiceError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.service] string '' The name or short description of the service.
[options.issue] string | undefined A description of the issue.

Example:

new ExternalServiceError() // There was an error with a remote service.
new ExternalServiceError({ service : 'Foo API' }) // The was an error with the Foo API remote service.
// v "The remote service is not responding."
new ExternalServiceError({ issue : 'is not responding' })
// v "The remote service Foo API is not responding."
new ExternalServiceError({ service : 'Foo API', issue : 'is not responding' })

UnavailableError source code global class index

An error indicating that the resource exists, but is not currently available. This represents a temporary condition.

Consider whether any of the following errors might be more precise or better suited:

Category: External service errors

new UnavailableError([options], defaults)

UnavailableError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} The constructor options.
[options.expectedTime] string | undefined A short description as to when the resource might be available. E.g., 'after 1400' or 'in two hours'.
[options.issue] string 'currently unavailable' -
[options.target] string 'target resource' The name of the function, endpoint, service, etc. which the user is trying to invoke. E.g., '/some/url/endpoint' or 'myFunction()'

Example:

new UnavailableError() // "The target resource is currently unavailable.
new UnavailableError({ target: 'URL /some/endpoint'}) // "The URL /some/endpoint is not currently available."
// v "The customer DB is offline for maintenance."
new UnavailableError({ target: 'customer DB', issue: 'offline for maintenance' })
// v "The URL /some/endpoint is not currently available; try again after 12:00 Saturday.'
new UnavailableError({ target: 'URL /some/endpoint', expectedTime: 'after 12:00 Saturday' })

NotImplementedError source code global class index

An error indicating the requested operation is not currently implemented.

Consider whether any of the following errors might be more precise or better suited:

Category: Feature errors

new NotImplementedError([options])

NotImplementedError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.target] string | undefined The name of the function, endpoint, service, etc. which the user is trying to invoke.

Example:

new NotImplementedError() // "Action not currently implemented."
new NotImplementedError({ target: '/some/url/endpoint'}) // "'/some/url/endpoint' is not currently implemented."

NotSupportedError source code global class index

An error indicating that the resource exists, but does not support some aspect of the request as is. This is most typically used when implementing a specification, but where some feature of the specification is not implemented. E.g., let's say a specification says requests can use JSON or YAML, but we only implement JSON support. If we get a request with a YAML payload, we could throw a NotSUpportedError.

Consider whether any of the following errors might be more precise or better suited:

Category: Feature errors

new NotSupportedError([options], defaults)

NotSupportedError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.missingFeature] string | undefined 'a requested feature' A short description of the action or thing which is not supported. E.g., 'YAML request payloads' or 'asynchronous execution'.
[options.hint] string | undefined A short hint to the user as to how they might resolve or workaround the issue. This should be a complete sentence. E.g., 'Encode request in JSON.' or 'Try synchronous execution.'
[options.target] string | undefined The name of the function, endpoint, service, etc. which the user is trying to invoke. E.g., '/some/url/endpoint' or 'myFunction()'

Example:

new NotSupportedError() // "The target does not currently support a requested feature."
// v "'/some/endpoint' does not currently support a requested feature."
new NotSupportedError({ target: '/some/endpoint'})
// v "'myFunc()' does not currently support RFC 3339 style dates."
new NotSupportedError({ target: 'myFunc()', issue: 'RFC 3339 style dates' })
// v "The target does not currently support YAML payloads. Send request in JSON."
new NotSupportedError({ issue: 'YAML payloads', hint : 'Send request in JSON.' })

CommonError source code global class index

A base class for common errors. To create a common error of your own, extend this class.

import { CommonError, registerParent } from 'standard-error-set'
const myName = 'MyError'

export const MyError = class extends CommonError {
  constructor({ name = myName, ...options}) {
    const message = "Now you've done it!"
    super({ name, message, ...options })
  }
}
MyError.typeName = myName

registerParent(myName, Object.getPrototypeOf(MyError).name)

If your new error creates a constructed message from parameters, refer to includeParameterInMessage and ArgumentInvalidError source code for an example of how to use it.

Category: General errors

new CommonError([options])

CommonError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
options.name string The name of error. In general, this should match the final class name.
[options.message] string 'An error has occurred.' The error message.
[options.code] string | undefined The error code.
[options.hint] string | undefined Optional hint regarding rectifying the error.
[options.status] number | undefined The HTTP status associated with the error. If undefined, this will be automatically set according to the [@link mapErrorToHttpStatus configured error mappings].
[options.options] object | undefined The options to pass to the Error super-constructor.

Example:

new CommonError() // "An error has occurred."
new CommonError({ message : 'Oh no! An error!' }) // "Oh no! An error!"

SystemError source code global class index

An error indicating a system error. When used to wrap native system errors (like ReferenceError, SyntaxError, etc.), be sure to set the cause option.

Category: General errors

new SystemError([options], defaults)

SystemError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.issue] string 'has experienced a system error' A description of the error.
[options.resource] string 'process' The name or short description of the resource where the error occurred.

Example:

new SystemError() // "The process has experienced a System."
// v "The application has experienced a stack overflow."
new SystemError({ resource: 'application'})

TimeoutError source code global class index

Indicates an operation is taking too much time.

Category: General errors

new TimeoutError([options], defaults)

TimeoutError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.resource] string | undefined The name or short description of the thing which is timing out.
[options.isLocal] boolean false Indicates whether the error arises from a remote service our not ( e.g., a connection timeout).

Example:

// new TimeoutError() // "The process has timed out."
// new TimeoutError({ resource : 'user session' }) // "The user session has timed out."

EndOfStreamError source code global class index

An IoError sub-type indicating an attempt to read beyond the of a stream.

Consider whether any of the following errors might be more precise or better suited:

Category: IO errors

new EndOfStreamError([options], defaults)

EndOfStreamError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string 'reading' A description of the action being taken; default to 'reading'.
[options.issue] string | undefined Describes the specific issue.
[options.target] string | undefined The name or description of the target resource.

Example:

new EndOfStreamError() // "There was an end-of-stream error."
new EndOfStreamError({ action : 'streaming' }) // "There was an end-of-stream error streaming."
new EndOfStreamError({ target : 'serial port' }) // "There was an end-of-stream error reading the serial port."
// v "There was an end-of-stream error streaming the serial port."
new EndOfStreamError({ action: 'streaming', target : 'serial port' })
// v "There was an end-of-stream error reading the serial port; virtual socket closed."
new EndOfStreamError({ issue : 'virtual socket closed', target : 'serial port' })

FileLoadError source code global class index

An IoError indicating a file is present, and can be read, but there is a problem loading it.

Consider whether any of the following errors might be more precise or better suited:

Category: IO errors

new FileLoadError([options], defaults)

FileLoadError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string 'loading' A description of the action being taken. Default to 'loading'.
[options.dirPath] string | undefined The directory (not including the file itself) where the file is located.
[options.fileName] string | undefined The name of the file itself. May be a full path (in which case dirPath should be left undefined) or just the file name, in which case it is combined with dirPath, if present, to create the standard error message.
[options.issue] string | undefined Describes the specific issue.
[options.target] string | undefined The name or description of the target resource. Should generally be left in preference for setting fileName and/or filePath.

Example:

new FileLoadError() // "There was an error loading the file."
new FileLoadError({ action : 'reading' }) // "There was an error reading the file."
new FileLoadError({ fileName : 'foo.txt' }) // "There an error loading the file 'foo.txt'."
new FileLoadError({ dirPath : '/bar', fileName: 'foo.txt' }) // "There an error loading the file '/bar/foo.txt'."
// v "There an error loading the file in directory '/bar'; virtual socket closed."
new FileLoadError({ issue : 'virtual socket closed', dirPath : '/bar' })

IoError source code global class index

A generic local I/O error not involving a missing resource. Note that IoErrors are specifically locally and external service, or remote connections errors are therefore not I/O errors.

Consider whether any of the following errors might be more precise or better suited:

Category: IO errors

new IoError([options], defaults)

IoError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.action] string | undefined A description of the action being taken. E.g., 'reading' or 'writing'. Defaults to 'accessing'.
[options.issue] string | undefined Describes the specific issue.
[options.target] string | undefined The name or description of the target resource.

Example:

new IoError() // "There was an IO error."
new IoError({ action : 'reading' }) // "There was an IO error while reading."
new IoError({ target : 'serial port' }) // "There an IO error while accessing the serial port."
new IoError({ action: 'reading', target : 'serial port' }) // "There an IO error while reading the serial port."
// v "There an IO error while accessing the serial port; virtual socket closed."
new IoError({ issue : 'virtual socket closed', target : 'serial port' })

DirectoryNotFoundError source code global class index

A NotFoundError sub-type indicating there is no file at the requested location. If both dirPath and fileName are specified, DirectoryNotFound tries to be smart about joining them and will try and guess the proper path separator and whether it needs to be appended or not.

Consider whether any of the following errors might be more precise or better suited:

Category: Not found errors

new DirectoryNotFoundError([options], defaults)

DirectoryNotFoundError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.dirPath] string | undefined The directory (not including the file itself) where the file is located.
[options.resource] string | undefined Should usually be left undefined. If set, then the value will override dirPath and be used to generate the standard message if message option not set.

Example:

new DirectoryNotFound() // "Directory not found."
new DirectoryNotFound({ dirPath: '/my-dir' }) // "Directory '/my-dir' not found."

FileNotFoundError source code global class index

A NotFoundError sub-type indicating there is no file at the requested location. If both dirPath and fileName are specified, FileNotFound tries to be smart about joining them and will try and guess the proper path separator and whether it needs to be appended or not.

Consider whether any of the following errors might be more precise or better suited:

Category: Not found errors

new FileNotFoundError([options], defaults)

FileNotFoundError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.dirPath] string | undefined The directory (not including the file itself) where the file is located.
[options.fileName] string | undefined The name of the file itself. May be a full path (in which case dirPath should be left undefined) or just the file name, in which case it is combined with dirPath, if present, to create the standard error message.
[options.resource] string | undefined Should usually be left undefined. If set, then the value will override fileName and dirPath and be used to generate the standard message if message option not set.

Example:

new FileNotFound() // "File not found."
new FileNotFound({ fileName: 'foo.txt' }) // "File 'foo.txt' not found."
new FileNotFound({ dirPath: '/tmp', fileName: 'foo.txt'}) // "File '/tmp/foo.txt' not found."
new FileNotFound({ dirPath: '/tmp/', fileName: 'foo.txt'}) // "File '/tmp/foo.txt' not found."
new FileNotFound({ dirPath: '/this-is-weird' }) // "File in directory '/this-is-weird' not found."

NotFoundError source code global class index

An error indicating a resource or entity cannot be found. This error is used with local and remote resources/entities where the fundamental issue is the named thing not being present.

Consider whether any of the following errors might be more precise or better suited:

Category: Not found errors

new NotFoundError([options], defaults)

NotFoundError constructor.

See the common constructor options note for additional parameters.

Param Type Default Description
[options] object {} Constructor options.
[options.resource] string | undefined The name or short description of the missing resource.
[options.code] string 'ENOENT' The code to use with the error. Should generally be left to the default.

Example:

new NotFoundError() // "Resource not found."
new NotFoundError({ resource : 'the hidden garden' }) // "The hidden garden is not found."

commonErrorSettings(option, value)* source code global function index

Used to retrieve and manage options used in wrapError and message construction.

Currently, we support three settings. Two influence the behavior of wrapError (refer to wrapError documentation for further details):

The third option ignoreForMessage (an array of string) specifies parameters to ignore when constructing an error message. This can be used to hide details from end users.

Param Type Description
option string | object Then name of the setting, or bulk settings Object.
value * The value of the setting. The necessary type depends on the option.

Returns: * - The value of the indicated option. The type will depend on the particular option.

Category: Settings management

mapErrorToHttpStatus(errorRef, status)number | undefined source code global function index

Used to translate and manage translation of error names to HTTP status codes. You can use this function to add your own mappings, which may be useful when dealing with non-common error errors.

Param Type Description
errorRef string | Error | CommonError.constructor | Object.<string, true> The name, instance, or class (instanceof ${linkplain CommonError)) of the error to either retrieve or set status for, or Object< string,true> `for bulk add/override of the custom mappings.
status number An integer value to map the error to.

Returns: number | undefined - Returns an integer if retrieving an error to status mapping, otherwise return undefined.

Category: Settings management

mapHttpStatusToName(status, name)string | undefined source code global function index

Used to translate and manage mappings from HTTP status codes to names. Supports all current status defined by the IANA, as well as common extensions returned by IIS, NginX, and Cloudflare.

Param Type Description
status number | Object.<number, string> Either the status to retrieve or set mapping for, or an Object<number,string> to bulk update mappings.
name string The name to map a status onto.

Returns: string | undefined - The status name, if known.

Category: Settings management

maskNoAccessErrors() source code global function index

Remaps NoAccessErrors (and all children) to a 404 (Not Found) status and changes the generated message. This will effectively remap and custom mappings of NoAccessError or it's children that may be in place. This is a common practice in secure systems where it is undesirable to give attackers any information about a resource they don't have access to. I.e., if a user tries to access a resource they are not permitted to access, an unmasked NoAccessError would divulge the existence of a resource. Note, this does not change the class of the error itself, so and developers should continue to use NoAccessErrors where the problem is actually access. In production systems, the presentation of errors to the users should not indicate the underlying type.

Category: Settings management

ignoreParameter(parameterName, options)boolean source code global function index

Determines whether a parameter should be ignored according to the provided options and global settings.

Param Type Default Description
parameterName string The name of the parameter to check.
options object The (relevant) constructor options.
[options.ignoreForMessage] Array.<string> [] List of parameter names which should be ignored in constructed error messages. Ignored parameter values revert to default or undefined.

Returns: boolean - A boolean indicating whether the named parameter should be ignored or not.

Category: Utility

includeParameterInMessage(parameterName, options)boolean source code global function index

Determines whether, based on parameter value and settings, whether the parameter should be used in creating a constructed message. If the parameter value is undefined or an empty array, then it is not included. Otherwise, options.ignoreForMessage or, if that is not defined, the common settings 'ignoreForMessage' setting is checked to see if the parameterName is included.

Param Type Description
parameterName string The name of the parameter to check.
options object The (relevant) constructor options.

Returns: boolean - A boolean indicating whether to include the parameter in the message construction or not.

Category: Utility

rethrowIf([error], [testOptions])Error | undefined source code global function index

One liner to test and re-throw errors if any conditions are met.

Param Type Default Description
[error] Error | undefined The Error to test against and possibly re-throw.
[testOptions] object {} The set of conditions to test against. If any of the conditions test true, then the error` is re-thrown.
[testOptions.codeIs] string | Array.<string> | undefined Throws if error.code is any of the listed codes.
[testOptions.codeIsNot] string | Array.<string> | undefined Throws if error.code is not any of the listed codes.
[testOptions.instanceOf] function | Array.<function()> | undefined Throws if error is an instance of any of the listed classes.
[testOptions.instanceOfNot] function | Array.<function()> | undefined Throws if error is not an instance of any of the listed classes.
[testOptions.isLocal] boolean | undefined If set, then tests whether the error is marked as 'isLocal' or not. Errors that do not expose this field directly are always considered local, except for instances of ExternalServiceError, which are always considered remote.
[testOptions.statusGt] number | undefined Throws if error.status is defined and status is greater than the specified status.
[testOptions.statusGte] number | undefined Throws if error.status is defined and status is greater than or equal to the specified status.
[testOptions.statusLt] number | undefined Throws if error.status is defined and status is less than the specified status.
[testOptions.statusLte] number | undefined Throws if error.status is defined and status is less than or equal to the specified status.
[testOptions.statusIs] number | Array.<number> | undefined Throws if error.status is defined and any of the specified statuses.
[testOptions.statusIsNot] number | Array.<number> | undefined Throws if error.status is defined and not any of the specified statuses.

Returns: Error | undefined - - If the function does not throw, it returns the error.

Category: Utility

wrapError(error, options)Array.<Error, boolean> source code global function index

Wraps an Error in a CommonError. The error parameter will be set as the cause field of the new CommonError instance (unless cause is specifically set in the options).

The wrapping logic is as follows:

Note, there is no special handling for EvalError (which is no longer in use) or CommonError (which is non-standard).

Param Type Description
error Error The Error to be wrapped.
options object | undefined The options controlling some wrapping and also passed to the wrapping CommonErrorconstructor.
options.noInstanceHidingOnWrap boolean If true, then if the error class is anything but Error, the original error will be return as is. If undefined, then the logic will refer to the commonErrorSettings noInstanceHidingOnWrap option value.
options.wrapUserErrorType function If set, then URIError, RangeError, and TypeError will be wrapped in a new error of that Class. Otherwise, the logic will refer to the commonErrorSettings wrapUserErrorType, which if undefined will result in the appropriate ArgumentInvalidError analog.

Returns: Array.<Error, boolean> - An array containing either the original Error or the new wrapping CommonError and a boolean indicating whether the error was wrapped (true) or not (false).

Category: Utility

Presenting errors to users

In a production system, the user should only see the error message, and additional information about the type of the error or where it occurred should not be passed on. This includes in response data which might not be directly displayed to the user, but could be accessed by inspecting the HTTP result, for instance. In particular, the class type and stack trace should not be included in any error response. If this protocol is adopted, then maskNoAccessErrors may be used.

If this information will be included in response data, then high security systems should use NotFoundError and it's children directly, even when the real problem is one off authorization. In this case, maskNoAccessErrors should not be used.