Error3 is an Error with extra powers. It has been designed to be extensible and easy to use. Though it has codes, message formatters and nested errors.
- Modern: designed for TypeScript and ES2019.
- IDE friendly: it's using classes and class fields to be inspectable for autosuggetion tools.
- i18n ready: formatter could produce localized messages with help of Intl API.
- Easy serialization and deserealization: good for network apps and JSON logging.
- Frontend caring: 0 dependencies, gzipped version is less then 1 KiB.
Table of Contents
Install
- In node.js:npm i error3
- In browser:CommonJS · UMD · ESM
⚠️ Remember about security! Add subresource integrity (SRI) checksum from checksum.txt.
Usage
Error3 suppose that you will create some base error class for your application or library and then use it as a parent for all your errors. Watch example in examples folder. Here it is interface realization:
code = 'fs_not_found' { return `File "" not found` }
This is what it gives to us:
const error = filepath: './index.js';error // -> "NotFoundErr: [#fs_not_found] File "./index.js" not found"errormessage // -> "File "./index.js" not found"errorcode // -> fs_not_founderrordetails // -> {filepath: './index.js'}
The same error TypeScript implementation:
JSON serialization
Calling Error3#toJSON()
on Error3 instance returns an object with properties
code
, message
, details
, and errors
. Example output:
Examples
API
Error3()
(details:object = {}, errors:Error[] = []) -> Error3
abstract. Both of Error3 constructor arguments are optional. The resposibility of
ancestor class is to implement proper interface and pass details
object
and errors
list into super()
call.
details
is using to describe error with JS primitives. Though it could be sent
via network to frontend, db, or ELK without extra parsing as it should be done
with regular Error instance.
TS Interface
Example
const error = userId: 1 'Collection removed'; errorcode // -> user_missederrormessage // -> User #1 not loadederrordetails // -> {userId: 1}errorerrors // -> [Error('Collection removed')]
Error#code
string|number
Error code should be a string or a number. It could be defined using class fields syntax:
code = 404
Error3#format()
(details: object, errors: Error[]) -> string
abstract. Creates formatted message string from details and other errors.
This method is calling from Error3 constrcutor to define message
property.
JS
{ return `Port is already in use` }
TS
Error3#toJSON()
Wrapper of Error3#valueOf
. It's created to be used by JSON.stringify()
.
Error3#valueOf()
() -> PlainError
This method realizes Object#valueOf()
behavior and returns plain error object containing properties:
code
, message
, details
and errors
.
PlainError{}
{
code: string|number,
message: string,
details: object,
errors: PlainError[],
}
It is a result of Error3#valueOf()
call.
License
MIT © Rumkin