@smallwins/err
Slightly better custom Error
s
- Same runtime interface: just pass a message to the constructor
- Respects
extends
with clean name
and stack
properties - Adds
toObject
returns a plain object representation - Bundles common HTTP error types with a
code
property
npm i @smallwins/err --save
Bundled Error Types
err.Err
a base Error
type intended for extendingerr.InternalError
has a code
property of 500
err.DatabaseError
has a code
property of 500
err.NotFoundError
has a code
property of 404
err.NotAuthorizedError
has a code
property of 403
Usage
Example usage:
var err = require('@smallwins/err')
let notFound = new err.NotFoundError('missing record')
console.log(err.code)
Subclass to add additional properties such as code
:
var err = require('@smallwins/err')
class CoffeeError extends err.Err {
constructor(params) {
super(params)
this.code = 500
}
}
let e = new CoffeeError('lactose intolerant')
console.log(e.code)
Get a clean representation:
console.log(e.toObject())
Extend by require
ing error directly:
var Err = require('@smallwins/err/err')
class TerribleError extends Err {
constructor(msg) {
super(msg)
this.extra = 'extra info'
}
}
var e = new TerribleError('wut')
console.log(e.extra)
Work oldschool without new
:
var err = require('@smallwins/err/oldschool')
console.log(err.Err('basic') instanceof Error)
console.log(err.NotFound('not found err').toString())
@smallwins/err/oldschool
API
Factory functions which return real Error
instances:
err.Err
returns an Err
instanceerr.Internal
returns an InternalError
instanceerr.Database
returns a DatabaseError
instanceerr.NotFound
returns a NotFoundError
instanceerr.NotAuthorized
returns a NotAuthorizedError
instance
Runtime type checking fully supported. Check the tests.