Handle errors in a simple, stable, consistent way. Features Simple patterns to: ⛑️ Create error classes 🏷️ Set error properties 🎀 Wrap or aggregate errors 🐞 Separate known and unknown errors Stability: 🚨 Normalize invalid errors 🛡️ 100% test coverage 🤓 Strict TypeScript types Plugins modern-errors-cli: Handle errors in CLI modules modern-errors-beautiful: Prettify error messages and stacks…
try{thrownewAuthError('...', innerOptions)}catch(cause){// `outerOptions` are merged with `innerOptions`thrownewBaseError('...',{...outerOptions, cause })}
try{throw'Missing file path.'}catch(invalidError){// This fails: `invalidError.message` is `undefined`
console.log(invalidError.message.trim())}
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())}
🐞 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` instancethrownewInputError('Invalid regular expression:',{cause: error })}
Normalizing unknown errors
If an error is not handled as described above, it is
considered unknown. This indicates an unexpected exception, usually a bug.
BaseError.normalize(error, UnknownError)
assigns the UnknownError class to those errors.
Most plugins can be configured with options. The option’s name is the same as
the plugin.
const options ={// `modern-errors-bugs` optionsbugs:'https://github.com/my-name/my-project/issues',// `props` can be configured and modified like plugin optionsprops:{userId:5},}
The custom option can be used to provide an error class
with additional methods, constructor, properties or options.
exportconst InputError = BaseError.subclass('InputError',{// The `class` must extend from the parent error classcustom:classextends 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 =newInputError('Wrong user name',{suffix:': example'})
console.log(error.message)// 'Wrong user name: example'
console.log(error.isUserInput())
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:
评论