2.0.4 • Published 7 years ago
@smallwins/err v2.0.4
@smallwins/err
Slightly better custom Error
s
- Same runtime interface: just pass a message to the constructor
- Respects
extends
with cleanname
andstack
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 baseError
type intended for extendingerr.InternalError
has acode
property of500
err.DatabaseError
has acode
property of500
err.NotFoundError
has acode
property of404
err.NotAuthorizedError
has acode
property of403
Usage
Example usage:
var err = require('@smallwins/err')
let notFound = new err.NotFoundError('missing record')
console.log(err.code) // logs 404
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) // logs 500
Get a clean representation:
console.log(e.toObject())
// logs {name, code, message, stack}
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)
// logs true
console.log(err.NotFound('not found err').toString())
// logs NotFound: not found err
@smallwins/err/oldschool
API
Factory functions which return real Error
instances:
err.Err
returns anErr
instanceerr.Internal
returns anInternalError
instanceerr.Database
returns aDatabaseError
instanceerr.NotFound
returns aNotFoundError
instanceerr.NotAuthorized
returns aNotAuthorizedError
instance
Runtime type checking fully supported. Check the tests.