Skip to content

Commit

Permalink
Add <Error>.subclass sugar
Browse files Browse the repository at this point in the history
  • Loading branch information
dasilvacontin committed Sep 7, 2015
1 parent d1eba2b commit 9ede91d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
21 changes: 21 additions & 0 deletions subclass-error.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@
root.SubclassError = factory()
}
}(this, function () {
/**
* Helper/sugar function so that you can do stuff like:
*
* ```js
* var ClientError = Error.subclass('ClientError', {code: 400})
* var ForbiddenError = ClientError.subclass('ForbiddenError', {code: 403})
* ```
*/
function SubclassSugar () {
// insert error constructor as second argument
Array.prototype.splice.call(arguments, 1, 0, this.prototype.constructor)
return SubclassError.SubclassError.apply(this, arguments)
}

var ErrorInheritor = function () {}
function SubclassError (name, BaseError, props) {
if (name === undefined) throw new Error('Name of subclass must be provided as first argument.')
Expand All @@ -34,6 +48,7 @@
if (message) goodStack[0] += ': ' + message
this.stack = goodStack.join('\n')
}
e.subclass = SubclassSugar
e.prototype = new ErrorInheritor()
e.prototype.constructor = e
e.prototype.name = name
Expand All @@ -43,5 +58,11 @@
return e
}

// ugly stuff so that spies can be used for testing
SubclassError.SubclassError = SubclassError

// add static sugar to Error
Error.subclass = SubclassSugar

return SubclassError
}))
24 changes: 24 additions & 0 deletions test/subclass-error.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,30 @@ describe('SubclassError', function () {
invalidName()
}).should.throw(/expect.*string/i)
})

describe.only('sugar', function () {
before(function () {
sinon.spy(SubclassError, 'SubclassError')
})

it('should populate error constructor argument', function () {
var subclassName = 'ClientError'
var props = {code: 400}
var ClientError = Error.subclass(subclassName, props)
SubclassError.SubclassError.should.have
.been.calledWith(subclassName, Error, props)

subclassName = 'ForbiddenError'
props = {code: 403}
var ForbiddenError = ClientError.subclass(subclassName, props)
SubclassError.SubclassError.should.have
.been.calledWith(subclassName, ClientError, props)
})

after(function () {
SubclassError.SubclassError.restore()
})
})
})

describe('instanceof', function () {
Expand Down

0 comments on commit 9ede91d

Please sign in to comment.