Created
August 28, 2017 03:30
-
-
Save refack/9b76413bab82f7d1c5fcf6f8320e5fba to your computer and use it in GitHub Desktop.
Snippet for https://github.com/nodejs/node/issues/15055
This file contains hidden or 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' | |
| const assert = require('assert'); | |
| class ExtendableError extends Error { | |
| constructor(message = '') { | |
| super(message); | |
| // extending Error is weird and does not propagate `message` | |
| Object.defineProperty(this, 'message', { | |
| configurable: true, | |
| enumerable : false, | |
| value : message, | |
| writable : true, | |
| }); | |
| Object.defineProperty(this, 'name', { | |
| configurable: true, | |
| enumerable : false, | |
| value : this.constructor.name, | |
| writable : true, | |
| }); | |
| if (Error.hasOwnProperty('captureStackTrace')) { | |
| Error.captureStackTrace(this, this.constructor); | |
| return; | |
| } | |
| Object.defineProperty(this, 'stack', { | |
| configurable: true, | |
| enumerable : false, | |
| value : (new Error(message)).stack, | |
| writable : true, | |
| }); | |
| } | |
| } | |
| class CustomError extends ExtendableError { | |
| constructor(message, httpStatusCode, data) { | |
| super(message); | |
| this.httpStatusCode = httpStatusCode; | |
| this.data = data; | |
| } | |
| toString() { | |
| const message = super.toString(); | |
| return ( | |
| this.data | |
| ? `${message}. Error data: ${JSON.stringify(this.data, null, 2)}` | |
| : message | |
| ); | |
| } | |
| } | |
| class NotFoundObject extends CustomError { | |
| constructor(objectId, objectType) { | |
| super(`${objectType || 'Object'} with id ${objectId} does not exist`, 400); | |
| } | |
| } | |
| const functionThatThrows = () => { | |
| throw new NotFoundObject('foo'); | |
| }; | |
| assert.throws(functionThatThrows, NotFoundObject); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment