Created
October 13, 2015 08:45
-
-
Save mprokopowicz/b510ac461d7bf095d94b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var assert = require('assert'); | |
var util = require('util'); | |
var NamedError = {}; | |
NamedError.NamedError = function(name, message) { | |
assert.strictEqual(typeof name, 'string', 'error name must be a string'); | |
if (typeof message !== 'undefined') { | |
assert.strictEqual(typeof message, 'string', 'error message must be a string'); | |
} | |
Error.captureStackTrace(this, NamedError.create); | |
this.name = name; | |
this.message = message ? util.format.apply(util, sliceArguments(arguments, 1)) : undefined; | |
return this; | |
}; | |
NamedError.create = function(name) { | |
var error = Object.create(NamedError); | |
return error.NamedError.apply(error, arguments); | |
}; | |
NamedError.handle = function(error, handlers) { | |
if (NamedError.isPrototypeOf(error) && error.name in handlers) { | |
handlers[error.name].call(error); | |
} else { | |
throw error; | |
} | |
}; | |
NamedError.setCode = function(code) { | |
assert.strictEqual(typeof code, 'number', 'code arg must be an number'); | |
this.code = code; | |
return this; | |
}; | |
NamedError.match = function(error, name) { | |
return NamedError.isPrototypeOf(error) && error.name === name; | |
}; | |
NamedError.setCause = function(cause) { | |
assert.strictEqual( | |
cause instanceof Error || NamedError.isPrototypeOf(cause), | |
true, | |
'cause must be either Error or NamedError instance' | |
); | |
this.cause = cause; | |
this.message += ': ' + cause.message; | |
return this; | |
}; | |
function sliceArguments(args, from) { | |
var argsLength = args.length; | |
var slicedArguments = new Array(argsLength - from); | |
for (var i = from, length = argsLength; i < length; i += 1) { | |
slicedArguments[i - from] = args[i]; | |
} | |
return slicedArguments; | |
} | |
module.exports = NamedError; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment