Custom Error Decorator
This is based on George Bailey's answerGeorge Bailey's answer, but extends and simplifies the original idea. It is written in CoffeeScript, but is easy to convert to JavaScript. The idea is extend Bailey's custom error with a decorator that wraps it, allowing you to create new custom errors easily.
Note: This will only work in V8. There is no support for Error.captureStackTrace
in other environments.
Define
The decorator takes a name for the error type, and returns a function that takes an error message, and encloses the error name.
CoreError = (@message) ->
@constructor.prototype.__proto__ = Error.prototype
Error.captureStackTrace @, @constructor
@name = @constructor.name
BaseError = (type) ->
(message) -> new CoreError "#{ type }Error: #{ message }"
Use
Now it is simple to create new error types.
StorageError = BaseError "Storage"
SignatureError = BaseError "Signature"
For fun, you could now define a function that throws a SignatureError
if it is called with too many args.
f = -> throw SignatureError "too many args" if arguments.length
This has been tested pretty well and seems to work perfectly on V8, maintaing the traceback, position etc.
Note: Using new
is optional when constructing a custom error.