Skip to content package
modern-errors v7.0.3 Handle errors in a simple, stable, consistent way
node >=18.18.0 9 deps esm types open source
overview readme
license MIT
deps 9
unpacked 94.1 kB
files 61
node >=18.18.0 $ npm install modern-errors@7.0.3n npmREADME GitHub-flavored package documentation.
downloads Across all versions.
Download trend unavailable.
compatibility Runtime metadata.
keywords Tagged topics.
nodejs javascript stacktrace library typescript browser errors monitoring error-monitoring message error-handler error-handling
versions Latest published Oct 9, 2025
maintainers Registry package owners.
install size Estimated unpacked size across 14 packages.
262.3 kB
Includes dependencies.
dependencies 10 direct dependencies.
Handle errors in a simple, stable, consistent way.
Features
Plugins
Example import ModernError from 'modern-errors'
export const BaseError = ModernError. subclass ( 'BaseError' )
export const UnknownError = BaseError. subclass ( 'UnknownError' )
export const InputError = BaseError. subclass ( 'InputError' )
export const AuthError = BaseError. subclass ( 'AuthError' )
export const DatabaseError = BaseError. subclass ( 'DatabaseError' ) copy throw new InputError ( 'Invalid file path' , { props: { filePath: '/...' } }) copy try {
// ...
} catch (cause) {
throw new InputError ( 'Could not read the file.' , { cause })
} copy try {
throw 'Missing file path.'
} catch (error) {
// Normalized from a string to a `BaseError` instance
throw BaseError. normalize (error)
} copy import ModernError from 'modern-errors'
import modernErrorsSerialize from 'modern-errors-serialize'
export const BaseError = ModernError. subclass ( 'BaseError' , {
plugins: [modernErrorsSerialize],
})
// ...
// Serialize error as JSON, then back to identical error instance
const error = new InputError ( 'Missing file path.' )
const errorString = JSON. stringify (error)
const identicalError = BaseError. parse (JSON. parse (errorString)) copy
Install npm install modern-errors copy If any plugin is used, it must also be installed.
npm install modern-errors-{pluginName} copy This package works in both Node.js >=18.18.0 and
browsers .
Usage
⛑️ Error classes
Create error classes import ModernError from 'modern-errors'
export const BaseError = ModernError. subclass ( 'BaseError' )
export const UnknownError = BaseError. subclass ( 'UnknownError' )
export const InputError = BaseError. subclass ( 'InputError' )
export const AuthError = BaseError. subclass ( 'AuthError' )
export const DatabaseError = BaseError. subclass ( 'DatabaseError' ) copy
Export error classes Exporting and documenting all error classes allows consumers to check them. This
also enables sharing error classes between modules.
Check error classes if (error instanceof InputError ) {
// ...
} copy
Error subclasses export const BaseError = ModernError. subclass ( 'BaseError' , {
props: { isError: true },
})
export const InputError = BaseError. subclass ( 'InputError' , {
props: { isUserError: true },
})
const error = new InputError ( '...' )
console. log (error.isError) // true
console. log (error.isUserError) // true
console. log (error instanceof BaseError ) // true
console. log (error instanceof InputError ) // true copy
🏷️ Error properties
Error class properties const InputError = BaseError. subclass ( 'InputError' , {
props: { isUserError: true },
})
const error = new InputError ( '...' )
console. log (error.isUserError) // true copy
Error instance properties const error = new InputError ( '...' , { props: { isUserError: true } })
console. log (error.isUserError) // true copy
Internal error properties Error properties that are internal or secret can be prefixed with _. This
makes them
non-enumerable ,
which prevents iterating or logging them.
const error = new InputError ( '...' , {
props: { userId: 6 , _isUserError: true },
})
console. log (error.userId) // 6
console. log (error._isUserError) // true
console. log (Object. keys (error)) // ['userId']
console. log (error) // `userId` is logged, but not `_isUserError` copy
🎀 Wrap errors
Throw errors throw new InputError ( 'Missing file path.' ) copy
Wrap inner error try {
// ...
} catch (cause) {
throw new InputError ( 'Could not read the file.' , { cause })
} copy
Wrap error message The outer error message is appended, unless it is empty. If the outer error
message ends with : or :\n, it is prepended instead.
const cause = new InputError ( 'File does not exist.' )
// InputError: File does not exist.
throw new InputError ( '' , { cause }) copy // InputError: File does not exist.
// Could not read the file.
throw new InputError ( 'Could not read the file.' , { cause }) copy // InputError: Could not read the file: File does not exist.
throw new InputError ( `Could not read the file:` , { cause }) copy // InputError: Could not read the file:
// File does not exist.
throw new InputError ( `Could not read the file: \n ` , { cause }) copy
Wrap error class The outer error's class replaces the inner one.
try {
throw new AuthError ( '...' )
} catch (cause) {
// Now an InputError
throw new InputError ( '...' , { cause })
} copy Except when the outer error's class is a parent class, such as
BaseError .
try {
throw new AuthError ( '...' )
} catch (cause) {
// Still an AuthError
throw new BaseError ( '...' , { cause })
} copy
Wrap error options try {
throw new AuthError ( '...' , innerOptions)
} catch (cause) {
// `outerOptions` are merged with `innerOptions`
throw new BaseError ( '...' , { ... outerOptions, cause })
} copy
Aggregate errors const databaseError = new DatabaseError ( '...' )
const authError = new AuthError ( '...' )
throw new InputError ( '...' , { errors: [databaseError, authError] })
// InputError: ... {
// [errors]: [
// DatabaseError: ...
// AuthError: ...
// ]
// } copy
🚨 Normalize errors
Wrapped errors try {
// ...
} catch (cause) {
throw new InputError ( '...' , { cause })
} copy
Invalid errors try {
throw 'Missing file path.'
} catch (invalidError) {
// This fails: `invalidError.message` is `undefined`
console. log (invalidError.message. trim ())
} copy try {
throw 'Missing file path.'
} catch (invalidError) {
const normalizedError = BaseError. normalize (invalidError)
// This works: 'Missing file path.'
// `normalizedError` is a `BaseError` instance.
console. log (normalizedError.message. trim ())
} copy
🐞 Unknown errors
Handling known errors Known errors should be handled in a try {} catch {} block and
wrapped with a specific class .
That block should only cover the statement that might throw in order to prevent
catching other unrelated errors.
try {
return regExp. test (value)
} catch (error) {
// Now an `InputError` instance
throw new InputError ( 'Invalid regular expression:' , { cause: error })
} copy
Normalizing unknown errors export const UnknownError = BaseError. subclass ( 'UnknownError' ) copy try {
return regExp. test (value)
} catch (error) {
// Now an `UnknownError` instance
throw BaseError. normalize (error, UnknownError)
} copy
Top-level error handler export const main = () => {
try {
// ...
} catch (error) {
throw BaseError. normalize (error, UnknownError)
}
} copy
🔌 Plugins
List of plugins Plugins extend modern-errors features. All available plugins are
listed here .
Adding plugins To use a plugin, please install it, then pass it to the
plugins option .
npm install modern-errors-{pluginName} copy import ModernError from 'modern-errors'
import modernErrorsBugs from 'modern-errors-bugs'
import modernErrorsSerialize from 'modern-errors-serialize'
export const BaseError = ModernError. subclass ( 'BaseError' , {
plugins: [modernErrorsBugs, modernErrorsSerialize],
})
// ... copy
Custom plugins
Plugin options Most plugins can be configured with options. The option's name is the same as
the plugin.
const options = {
// `modern-errors-bugs` options
bugs: 'https://github.com/my-name/my-project/issues' ,
// `props` can be configured and modified like plugin options
props: { userId: 5 },
} copy Plugin options can apply to (in priority order):
export const BaseError = ModernError. subclass ( 'BaseError' , options) copy export const InputError = BaseError. subclass ( 'InputError' , options) copy throw new InputError ( '...' , options) copy
A plugin method call: last argument, passing only that plugin's options
ErrorClass[methodName]( ... args, options[pluginName]) copy error[methodName]( ... args, options[pluginName]) copy
🔧 Custom logic The custom option can be used to provide an error class
with additional methods, constructor, properties or options.
export const InputError = BaseError. subclass ( 'InputError' , {
// The `class` must extend from the parent error class
custom: class extends BaseError {
// If a `constructor` is defined, its parameters must be (message, options)
// Additional `options` can be defined.
constructor (message, options) {
message += options?.suffix ?? ''
super (message, options)
}
isUserInput () {
// ...
}
},
})
const error = new InputError ( 'Wrong user name' , { suffix: ': example' })
console. log (error.message) // 'Wrong user name: example'
console. log (error. isUserInput ()) copy
🤓 TypeScript
API
ModernError
ErrorClass.subclass(name, options?) Creates and returns a child ErrorClass.
options
options.props
options.plugins
options.custom Type : class extends ErrorClass {}
options.*
new ErrorClass(message, options?)
options
options.props
options.cause
options.errors
options.*
ErrorClass.normalize(error, NewErrorClass?) error: Error | any
NewErrorClass: subclass of ErrorClass
Return value : Error
If error is an instance of ErrorClass (or one of its subclasses), it is left
as is. Otherwise, it is
converted to NewErrorClass , which defaults to
ErrorClass itself.
Modules This framework brings together a collection of modules which can also be used
individually:
Support Everyone is welcome regardless of personal background. We enforce a
Code of conduct in order to promote a positive and
inclusive environment.
Contributing This project was made with ❤️. The simplest way to give back is by starring and
sharing it online.
If the documentation is unclear or has a typo, please click on the page's Edit
button (pencil icon) and suggest a correction.
If you would like to help us fix a bug or add a new feature, please check our
guidelines . Pull requests are welcome!