standard-error-set
v1.0.0-beta.2
Published
A collection of common/standard error types to flesh out Javascripts rather anemic baseline.
Downloads
7
Readme
standard-error-set
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
- Set of expressive, semantic error classes.
- Built in, configurable HTTP status codes and names.
- All classes support standard, parameterized constructed and full custom messages.
- Automatically wrap standard
Error
classes and codes in semantically strongError
s. - One-line re-throw testing.
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.
cause
(Error
|undefined
): The error that caused this error. This is useful for wrapping a more generic error in a more specific error or chaining related errors across an error boundary (e.g., asynchronous calls).hint
(string
|undefined
): Optional hint regarding how to rectify the error. This should be a complete sentence and, if defined, will be appended to themessage
(whether defined directly or constructed).ignoreForMessage
(string[]|undefined
): When set, the named options name options will be ignored if/when constructing the message. Ignored values are treated as 'unset' and will either be left out of the message entirely or revert to default values based on the error type. If the special value 'all' is included, then all parameters will be ignored. This is useful when, for instance, you want to hide information from the user about specific resources, actions, required authorizations, etc., but you still want to include these parameters as part of the error instance for logging or other purposes.message
(string
|undefined
): AllCommonError
classes generate a standard message, based on class specific input parameters (if any). You can always override this message and provide your own custom message.status
(number
|undefined
): AllCommonError
classes are assigned an HTTP status based on their error type. The mapping between error type and status code can be managed withmapErrorToHttpStatus
. This would be unusual, but you can instead set the status on a particularCommonError
instance with this option.
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.
- All non-common constructor options are used in message construction. Since common parameters are not included in class documentation, all parameters in the class documentation are used in generating a constructed message. Refer to class documentation for example constructed messages.
- All construction parameters are optional and all
CommonError
and sub-classes will generate a standard class specific message if given no options. - All constructors take the
hint
option, which, if specified, will be appended to themessage
(whether constructed or specified). - Parameters can be ignored in message construction by setting the
ignoreForMessage
option.
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.
- Classes:
- Argument errors
ArgumentInvalidError
: Indicates an invalid argument which by default is interpreted as a user supplied argument/input.ArgumentMissingError
: AnArgumentInvalidError
sub-type indicating a argument is missing or empty which by default is interpreted as a user supplied argument/input.ArgumentOutOfRangeError
: AnArgumentInvalidError
sub-type indicating a (typically user supplied) argument is of the correct time, but outside the acceptable range.ArgumentTypeError
: AnArgumentInvalidError
sub-type indicating a (typically user supplied) argument is not the correct type.
- Auth errors
AuthenticationRequiredError
: AnAuthError
sub-class indicating that an operation requires an authenticated user and the current us not authenticated.AuthError
: A generic error indicating a problem with user authentication or authorization.AuthorizationConditionsNotMetError
: AnAuthError
indicating that the user is authorized to perform some action under some circumstances, but additional conditions must be met.BadCredentialsError
: AnAuthError
sub-class indicating the provided credentials are invalid.NoAccessDirectoryError
: AnNoAccessError
indicating a user lacks the rights to access a particular directory.NoAccessError
: AnAuthError
indicating a user lacks the rights to access a particular resource.NoAccessFileError
: AnNoAccessError
indicating a user lacks the rights to access a particular file.OperationNotPermittedError
: AnAuthError
indicating the user lacks authorization to perform some operation.
- Database errors
ConstraintViolationError
: Indicates the requested operation is well formed and the data otherwise correct, but it violates a data constraint.DatabaseError
: Indicates a problem within a database system implementation.RollbackError
: AnDatabaseError
sub-type relating to a failed rollback within a database.TransactionError
: AnDatabaseError
indicating a problem creating or otherwise involving a transaction within a database system itself.UniqueConstraintViolationError
: AConstraintViolationError
sub-type indicating violation of a unique constraint, such as login ID.
- External service errors
ConnectionError
: AnExternalServiceError
sub-type indicating a problem with a connection, including making a connection.ExternalServiceError
: Indicates an error related to an external service.UnavailableError
: An error indicating that the resource exists, but is not currently available.
- Feature errors
NotImplementedError
: An error indicating the requested operation is not currently implemented.NotSupportedError
: An error indicating that the resource exists, but does not support some aspect of the request as is.
- General errors
CommonError
: A base class for common errors.SystemError
: An error indicating a system error.TimeoutError
: Indicates an operation is taking too much time.
- IO errors
EndOfStreamError
: AnIoError
sub-type indicating an attempt to read beyond the of a stream.FileLoadError
: AnIoError
indicating a file is present, and can be read, but there is a problem loading it.IoError
: A generic local I/O error not involving a missing resource.
- Not found errors
DirectoryNotFoundError
: ANotFoundError
sub-type indicating there is no file at the requested location.FileNotFoundError
: ANotFoundError
sub-type indicating there is no file at the requested location.NotFoundError
: An error indicating a resource or entity cannot be found.
- Argument errors
- Functions:
- Settings management
commonErrorSettings()
: Used to retrieve and manage options used inwrapError
and message construction.mapErrorToHttpStatus()
: Used to translate and manage translation of error names to HTTP status codes.mapHttpStatusToName()
: Used to translate and manage mappings from HTTP status codes to names.maskNoAccessErrors()
: RemapsNoAccessError
s (and all children) to a 404 (Not Found) status and changes the generated message.
- Utility
ignoreParameter()
: Determines whether a parameter should be ignored according to the provided options and global settings.includeParameterInMessage()
: Determines whether, based on parameter value and settings, whether the parameter should be used in creating a constructed message.rethrowIf()
: One liner to test and re-throw errors if any conditions are met.wrapError()
: Wraps anError
in aCommonError
.
- Settings management
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:
ArgumentMissingError
- For when the argument is required, but missing or empty.ArgumentOutOfRangeError
- For when the argument is of the proper type, but outside the acceptable range.ArgumentTypeError
- Indicates an argument is an incorrect type.
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 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 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:
ArgumentInvalidError
- General argument error when no more specific error fits.ArgumentOutOfRangeError
- Indicates an argument is of the correct type, but outside the acceptable range.ArgumentTypeError
- Indicates an argument is an incorrect type.
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:
ArgumentInvalidError
- General argument error when no more specific error fits.ArgumentMissingError
- For when the argument is required, but missing or empty.ArgumentTypeError
- Indicates an argument is an incorrect type.
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:
ArgumentInvalidError
- General argument error when no more specific error fits.ArgumentMissingError
- Indicates the argument is missing or empty.ArgumentOutOfRangeError
- Indicates an argument is of the correct type, but outside the acceptable range.
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:
AuthenticationRequiredError
- Use this when the resource requires authenticated access and the user is not currently authenticated.NoAccessError
- Use this when the user is accessing a resource the user has no authorizations to.OperationNotPermittedError
- Use this when user is attempting an operation for which they have no authorization.
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:
AuthenticationRequiredError
- Use this when the resource requires authenticated access and the user is not currently authenticated.AuthorizationConditionsNotMetError
- Use this when the user is authorized to access the directory under some conditions.NoAccessError
NoAccessFileError
OperationNotPermittedError
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:
AuthenticationRequiredError
- Use this when the resource requires authenticated access and the user is not currently authenticated.AuthorizationConditionsNotMetError
- Use this when the user is authorized to access the resource under some conditions.NoAccessDirectoryError
NoAccessFileError
OperationNotPermittedError
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:
AuthenticationRequiredError
- Use this when the resource requires authenticated access and the user is not currently authenticated.AuthorizationConditionsNotMetError
- Use this when the user is authorized to access the file under some conditions.NoAccessDirectoryError
NoAccessError
OperationNotPermittedError
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:
AuthenticationRequiredError
AuthorizationConditionsNotMetError
- Use this when the user is authorized to perform the operation under some conditions.BadCredentialsError
AuthorizationConditionsNotMetError
NoAccessError
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([email protected])> on entity type 'user' violated."
new ConstraintViolationError({ entityType : 'user', fieldAndValues : [['email', '[email protected]']] })
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([email protected])> on entity type 'user' violated."
new UniqueConstraintViolationError({ entityType : 'user', fieldAndValues : [['email', '[email protected]']] })
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:
ConnectionError
DatabaseError
and sub-types are used with database specific issues.TimeoutError
UnavailableError
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:
NotImplementedError
- Use this when the target is not implemented at all.NotSupportedError
- Use this when the target is implemented, but doesn't support some requested feature.
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:
NotSupportedError
- Use this when the target is implemented, but does not support some feature or condition captured in the request.UnavailableError
- Use this when a resource exists, but is temporarily unavailable for some reason.
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:
NotImplementedError
- Use this when the target is not implemented at all.UnavailableError
- Use this when the target is implemented, but temporarily unavailable for some reason.
Category: Feature errors
new NotSupportedError([options], defaults)
NotSupportedError
constructor.
See the [common constructor options](