Created
October 22, 2015 14:36
-
-
Save blamattina/6b0d8707dad08293fd6d 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
define [ | |
'underscore' | |
], (_) -> | |
Object.defineProperty Error.prototype, 'toJSON', | |
configurable: true | |
value: -> | |
json = {} | |
Object.getOwnPropertyNames(this).forEach (prop) => | |
if this[prop] instanceof Error | |
json[prop] = this[prop].toJSON() | |
else | |
json[prop] = this[prop] | |
json | |
# Supported syntax | |
# | |
# @example | |
# Class MyError extends BaseError | |
# name: 'MyError' | |
# code: 'my_error' | |
# severity: MyError::FATAL | |
# friendlyMessage: 'Something has gone awry!' | |
# | |
# throw new MyError(someOtherError) | |
# => 'MyError: the other errors message' | |
# | |
# throw new MyError('well darn.') | |
# => 'MyError: well darn.' | |
# | |
# throw new MyError({some: 'object'}) | |
# => 'MyError: {some: 'object'}' | |
class BaseError extends Error | |
TYPES: | |
WRAPPED: 'wrapped' | |
BASIC: 'basic' | |
JSON: 'json' | |
FATAL: 'fatal' | |
INFO: 'info' | |
name: undefined | |
constructor: (cause) -> | |
@context = [] | |
if cause instanceof Error | |
@type = @TYPES.WRAPPED | |
@message = "#{@name}: #{cause.message}" | |
@cause = cause | |
@stack = cause.stack | |
else if typeof cause is 'string' | |
@type = @TYPES.WRAPPED | |
@stack = new Error().stack | |
@_message = cause | |
else | |
@type = @TYPES.JSON | |
@message = JSON.stringify cause | |
@_validateErrorClass() | |
addContext: (context) -> | |
@context.push(context) | |
undefined | |
_validateErrorClass: -> | |
REQUIRED_PROPERTIES = ['name', 'friendlyMessage', 'code', 'severity'] | |
_(REQUIRED_PROPERTIES).each (prop) => | |
unless @[prop] | |
console.error "Implementation Error: required property '#{prop}' | |
is not defined. Typically this happens when | |
BaseError has been extended and required properties | |
have not been defined." | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment