Skip to content

Instantly share code, notes, and snippets.

@jcayzac
Created February 12, 2014 07:28
Show Gist options
  • Select an option

  • Save jcayzac/8951348 to your computer and use it in GitHub Desktop.

Select an option

Save jcayzac/8951348 to your computer and use it in GitHub Desktop.
// Proper exceptions in JS:
function MakeErrorClass(name, parent) {
parent = parent || Error
var cls = function(message) {
parent.call(this, arguments)
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor)
else
this.stack = [name].concat(Error().stack.split('\n').slice(3)).join('\n')
this.message = message
Object.freeze(this)
}
cls.prototype = Object.create(parent.prototype, {name: {value: name, enumerable: true}})
cls.prototype.constructor = cls
return cls
}
// Example:
var MyError = MakeErrorClass('MyError')
var SubError = MakeErrorClass('SubError', MyError)
try {
throw new SubError('foo')
} catch (e) {
console.log(e instanceof MyError ? 'Got a MyError!' : 'Got an unknown error!')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment