Skip to content

Instantly share code, notes, and snippets.

@refack
Created August 28, 2017 03:30
Show Gist options
  • Select an option

  • Save refack/9b76413bab82f7d1c5fcf6f8320e5fba to your computer and use it in GitHub Desktop.

Select an option

Save refack/9b76413bab82f7d1c5fcf6f8320e5fba to your computer and use it in GitHub Desktop.
'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