// From a stringconst err = errs.create('Something went wrong')// From an objectconst err = errs.create({ message: 'Database connection failed', status: 500, code: 'DB_ERROR'})// From an array (joined with spaces)const err = errs.create(['Invalid', 'request', 'parameters'])// From a functionconst err = errs.create(() => ({ message: 'Dynamic error', timestamp: Date.now()}))
errs.create(type, opts)
Creates an error of a registered type.
class ValidationError extends Error { name = 'ValidationError'}errs.register('validation', ValidationError)const err = errs.create('validation', { message: 'Invalid input', field: 'email'})
Merging Errors
errs.merge(error, opts)
Merges an existing error with new properties and sets native cause chain.
Assert error is a specific type, throws TypeError if not.
function handleHttpError(err) { // Throws TypeError if err is not HttpError const httpErr = errs.assertErrorType(err, HttpError) return httpErr.status // TypeScript knows this is HttpError}
Result Pattern
errs.tryCatch(fn)
Wraps a sync function to return a Result instead of throwing.
// Terminal output with colorsconsole.log(errs.format(error, { format: 'terminal', colors: true }))// JSON for logginglogger.error(errs.format(error, { format: 'json', indent: 2 }))// HTML for error pagesres.send(errs.format(error, { format: 'html' }))
Terminal Output:
╭─ TypeError: Cannot read property 'x' of undefined││ at processUser (src/users.js:42:15)│ at async main (src/index.js:10:3)│├─ Caused by: NetworkError: Connection refused││ at fetch (src/api.js:23:9)│╰─ 2 errors in chain
Error Handling
errs.handle(error, callback, stream)
Unified error handling for callbacks and EventEmitters.
// With callbackerrs.handle(err, (e) => console.error(e))// With EventEmittererrs.handle(err, emitter)// With botherrs.handle(err, callback, emitter)// Returns emitter if no callbackconst emitter = errs.handle(err)emitter.on('error', handleError)
Type Registration
errs.register(type, ErrorClass)
Register a custom error type.
class HttpError extends Error { name = 'HttpError' constructor(message, status) { super(message) this.status = status }}errs.register('http', HttpError)// Use registered typeconst err = errs.create('http', { message: 'Not found', status: 404})