Skip to content

Commit

Permalink
feat(core): stackable errors
Browse files Browse the repository at this point in the history
allows for errors to be passed as the contructor argument
  • Loading branch information
Ahmad Nassri committed Dec 10, 2016
1 parent 9856fce commit 0ffde80
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
'use strict'

module.exports = class ExtendableError extends Error {
constructor (message) {
super(message)
constructor (input) {
const isError = Object.prototype.toString.call(input) === '[object Error]' || input instanceof Error

this.name = this.constructor.name
const message = (isError ? input.message : input) || ''

super(message)
this.message = message
this.name = this.constructor.name

// inherit properties
if (isError) {
Object.assign(this, input)
}

if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor)
} else {
this.stack = (new Error(message)).stack
this.stack = new Error(message).stack
}
}
}
34 changes: 34 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,19 @@ class SubTestError extends TestError {}

const regex = /(\w|\/)+test\/index\.js:\d{2}:\d{2}/

test('Empty ExtendableError', assert => {
assert.plan(5)

let err = new ExtendableError()

assert.type(err, ExtendableError)

assert.equal(err.name, 'ExtendableError')
assert.equal(err.message, '')
assert.match(err.stack, regex)
assert.equal(err.toString(), 'ExtendableError')
})

test('ExtendableError instance of Error', assert => {
assert.plan(6)

Expand Down Expand Up @@ -53,6 +66,27 @@ test('SubTestError instance of TestError', assert => {
assert.equal(err.toString(), 'SubTestError: error occurred')
})

test('Stacking Errors', assert => {
assert.plan(6)

let error = new Error('error occurred')
error.code = 10
error.foo = 'bar'

let err = new ExtendableError(error)

assert.type(err, ExtendableError)
assert.type(err, Error)

assert.equal(err.code, 10)
assert.equal(err.foo, 'bar')
assert.equal(err.name, 'ExtendableError')
assert.equal(err.toString(), 'ExtendableError: error occurred')

assert.end()
})

// must be last, breaks tap otherwise
test('Manual captureStackTrace', assert => {
assert.plan(6)

Expand Down

0 comments on commit 0ffde80

Please sign in to comment.