New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

trace-error

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

trace-error - npm Package Compare versions

Comparing version 1.0.0 to 1.0.1

.travis.yml

229

dist/TraceError.js

@@ -1,77 +0,194 @@

'use strict';
"use strict";
exports.__esModule = true;
require("core-js/modules/es.symbol");
require("core-js/modules/es.symbol.description");
require("core-js/modules/es.symbol.iterator");
require("core-js/modules/es.array.concat");
require("core-js/modules/es.array.iterator");
require("core-js/modules/es.array.join");
require("core-js/modules/es.object.get-own-property-descriptor");
require("core-js/modules/es.object.get-prototype-of");
require("core-js/modules/es.object.to-string");
require("core-js/modules/es.reflect.get");
require("core-js/modules/es.string.iterator");
require("core-js/modules/es.string.split");
require("core-js/modules/es.string.trim");
require("core-js/modules/web.dom-collections.iterator");
var _Exception2 = _interopRequireDefault(require("./Exception"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
var TraceError = function (_Error) {
_inherits(TraceError, _Error);
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function TraceError(message) {
for (var _len = arguments.length, causes = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
causes[_key - 1] = arguments[_key];
}
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
_classCallCheck(this, TraceError);
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
var _this = _possibleConstructorReturn(this, _Error.call(this, message));
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var stack = Object.getOwnPropertyDescriptor(_this, 'stack');
function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
Object.defineProperty(_this, 'stack', {
get: function get() {
var stacktrace = _this.customFormat || _this.customFormat2 || stack.get.call(_this);
var causeStacktrace = '';
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
for (var _iterator = causes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var TraceError =
/*#__PURE__*/
function (_Exception) {
_inherits(TraceError, _Exception);
_createClass(TraceError, [{
key: "serializeNonError",
value: function serializeNonError(e) {
try {
return JSON.stringify(e, null, 2);
} catch (e) {// ignore
}
return e;
}
}, {
key: "resolveStackFromError",
value: function resolveStackFromError(e) {
return e === this && TraceError.globalStackProperty === 'stack' ? // use the parent stack to prevent stack overflow
_get(_getPrototypeOf(TraceError.prototype), "stack", this) : // no need to check type since the fallback is the Error.prototype
e[TraceError.globalStackProperty];
}
}, {
key: "getLongStack",
value: function getLongStack() {
var stacks = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.causes()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var cause = _step.value;
if (cause instanceof TraceError) {
stacks.push(cause.getLongStack());
} else if (cause instanceof Error) {
stacks.push(this.resolveStackFromError(cause));
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
stacks.push(this.serializeNonError(cause));
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var cause = _ref;
var children = TraceError.indent + stacks.join('\n').split('\n').join('\n' + TraceError.indent);
return (this.resolveStackFromError(this) + '\n' + children).trim();
}
}, {
key: "messages",
value: function messages() {
var messages = [_get(_getPrototypeOf(TraceError.prototype), "message", this)];
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
if (cause.customFormat) {
// trigger lookup
causeStacktrace += '\n' + cause.customFormat;
} else if (cause.customFormat2) {
causeStacktrace += '\n' + cause.customFormat2;
try {
for (var _iterator2 = this.causes()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var cause = _step2.value;
if (cause instanceof TraceError) {
messages = messages.concat(cause.messages());
} else if (cause instanceof Error) {
causeStacktrace += '\n' + cause.stack;
messages.push(cause.message);
} else {
try {
var json = JSON.stringify(cause, null, 2);
causeStacktrace += '\n' + json;
} catch (e) {
causeStacktrace += '\n' + cause;
// ignore
}
messages.push(cause);
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
causeStacktrace = causeStacktrace.split('\n').join('\n ');
return stacktrace + causeStacktrace;
return messages;
}
}, {
key: "cause",
value: function cause() {
var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return this.getHiddenProperty('causes', [])[index];
}
}, {
key: "causes",
value: function causes() {
return this.getHiddenProperty('causes', []);
}
}, {
key: "stack",
get: function get() {
if (this.getHiddenProperty('useBase')) {
return _get(_getPrototypeOf(TraceError.prototype), "stack", this);
}
});
// access first error
Object.defineProperty(_this, 'cause', { value: function value() {
return causes[0];
}, enumerable: false, writable: false });
this.defineHiddenProperty('useBase', true);
var stack = this.getLongStack();
this.defineHiddenProperty('useBase', false);
return stack;
}
}]);
// untested; access cause stack with error.causes()
Object.defineProperty(_this, 'causes', { value: function value() {
return causes;
}, enumerable: false, writable: false });
function TraceError(message) {
var _this;
_classCallCheck(this, TraceError);
_this = _possibleConstructorReturn(this, _getPrototypeOf(TraceError).call(this, message));
for (var _len = arguments.length, causes = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
causes[_key - 1] = arguments[_key];
}
_this.defineHiddenProperty('causes', causes);
return _this;

@@ -81,4 +198,10 @@ }

return TraceError;
}(Error);
}(_Exception2.default);
exports.default = TraceError;
_defineProperty(TraceError, "indent", ' ');
_defineProperty(TraceError, "globalStackProperty", 'stack');
_defineProperty(TraceError, "Exception", _Exception2.default);
module.exports = TraceError;
{
"name": "trace-error",
"version": "1.0.0",
"version": "1.0.1",
"description": "Chained errors for JavaScript",
"main": "index.js",
"main": "dist/TraceError.js",
"scripts": {
"test": "./node_modules/mocha/bin/mocha ./tests/*-test.js"
"test": "./node_modules/mocha/bin/mocha ./tests/*-test.js",
"build": "npx babel src --out-dir dist"
},

@@ -21,3 +22,3 @@ "repository": {

"author": "Mathew Kurian",
"license": "ISC",
"license": "MIT",
"bugs": {

@@ -28,9 +29,13 @@ "url": "https://github.com/bluejamesbond/TraceError.js/issues"

"devDependencies": {
"babel-preset-es2015": "6.6.0",
"babel-preset-es2015-loose": "7.0.0",
"grunt": "0.4.5",
"grunt-babel": "6.0.0",
"load-grunt-tasks": "3.4.1",
"mocha": "2.4.5"
"@babel/cli": "^7.4.3",
"@babel/core": "^7.4.3",
"@babel/polyfill": "^7.4.0",
"@babel/preset-env": "^7.4.2",
"@babel/plugin-proposal-class-properties": "^7.4.0",
"mocha": "^4.0.0"
},
"dependencies": {
"core-js": "3",
"weakmap": "0.0.6"
}
}
# TraceError
[![Build Status](https://travis-ci.org/mathew-kurian/TraceError.js.svg?branch=master)](https://travis-ci.org/bluejamesbond/TraceError.js)
```bash
npm install trace-error --save
```
```js
throw new TraceError('Could not set status', srcError, ...otherErrors);
import TraceError from 'trace-error';
global.TraceError = TraceError; // expose globally (optional)
(async () => {
try {
await fetch('google.com');
} catch(e) {
console.error(new TraceError('Failed to fetch content', e));
}
})();
```
## Output
![](https://www.dropbox.com/s/gbfoh4sr9p24hsg/Screenshot%202016-03-01%2022.26.27.png?dl=1)
### Output
```bash
TraceError: Failed to fetch content
at _construct (.../TraceError.js/dist/Exception.js:35:393)
at TraceError.Exception (.../TraceError.js/dist/Exception.js:110:17)
at new TraceError (.../TraceError.js/dist/TraceError.js:186:74)
at .../TraceError.js/tests/throw-test.js:159:19
at Object.<anonymous> (.../TraceError.js/tests/throw-test.js:161:3)
ReferenceError: fetch is not defined
at .../TraceError.js/tests/throw-test.js:157:5
at Object.<anonymous> (.../TraceError.js/tests/throw-test.js:161:3)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
```
#### Compatibility
Node >= 4.0; not tested on browsers
## Functions
#### `TraceError#cause(index = 0)`
Get the cause at the specified `index`
#### `TraceError#causes()`
Get a list of all the causes
#### `TraceError@stack`
Get the long stack (base error with chained cause errors)
#### `TraceError@messages`
Get a list of all the messages
#### `static TraceError@globalStackProperty`
Attribute used to aggregate the long stack. Can be further customized via. inheritance and/or prototype modification
#### `static TraceError@indent`
Spaces used to indent long stack
## More Detailed Examples
More detailed examples are in the `/tests` folder
### ES5/6 Cross-compatibility
Extend the TraceError as such in order to maximize compatibility with ES5; additionally, override the `toJSON` as necessary
```js
TraceError#cause - first error
TraceError#causes - list of chained errors
export class MyAppTraceError extends TraceError {
constructor(...args) {
super(...args);
// not ideal
Object.defineProperty(this, 'stack', {
get: () => super.stack
});
}
}
```

@@ -1,42 +0,88 @@

export default class TraceError extends Error {
constructor(message, ...causes) {
super(message);
import Exception from './Exception';
const stack = Object.getOwnPropertyDescriptor(this, 'stack');
class TraceError extends Exception {
static indent = ' ';
static globalStackProperty = 'stack';
static Exception = Exception;
Object.defineProperty(this, 'stack', {
get: () => {
const stacktrace = this.customFormat || this.customFormat2 || stack.get.call(this);
let causeStacktrace = '';
serializeNonError(e) {
try {
return JSON.stringify(e, null, 2);
} catch (e) {
// ignore
}
for (const cause of causes) {
if (cause.customFormat) { // trigger lookup
causeStacktrace += `\n${cause.customFormat}`;
} else if (cause.customFormat2) {
causeStacktrace += `\n${cause.customFormat2}`;
} else if (cause instanceof Error) {
causeStacktrace += `\n${cause.stack}`;
} else {
try {
const json = JSON.stringify(cause, null, 2);
causeStacktrace += `\n${json}`;
} catch (e) {
causeStacktrace += `\n${cause}`;
// ignore
}
}
}
return e;
}
causeStacktrace = causeStacktrace.split('\n').join('\n ');
resolveStackFromError(e) {
return e === this && TraceError.globalStackProperty === 'stack' ?
// use the parent stack to prevent stack overflow
super.stack :
// no need to check type since the fallback is the Error.prototype
e[TraceError.globalStackProperty];
}
return stacktrace + causeStacktrace;
getLongStack() {
const stacks = [];
for (const cause of this.causes()) {
if (cause instanceof TraceError) {
stacks.push(cause.getLongStack())
} else if (cause instanceof Error) {
stacks.push(this.resolveStackFromError(cause));
} else {
stacks.push(this.serializeNonError(cause));
}
});
}
// access first error
Object.defineProperty(this, 'cause', {value: () => causes[0], enumerable: false, writable: false});
const children = TraceError.indent + stacks.join('\n').split('\n').join('\n' + TraceError.indent);
return (this.resolveStackFromError(this) + '\n' + children).trim();
}
// untested; access cause stack with error.causes()
Object.defineProperty(this, 'causes', {value: () => causes, enumerable: false, writable: false});
get stack() {
if (this.getHiddenProperty('useBase')) {
return super.stack;
}
this.defineHiddenProperty('useBase', true);
const stack = this.getLongStack();
this.defineHiddenProperty('useBase', false);
return stack;
}
}
messages() {
let messages = [super.message];
for (const cause of this.causes()) {
if (cause instanceof TraceError) {
messages = messages.concat(cause.messages());
} else if (cause instanceof Error) {
messages.push(cause.message);
} else {
messages.push(cause);
}
}
return messages;
}
cause(index = 0) {
return this.getHiddenProperty('causes', [])[index];
}
causes() {
return this.getHiddenProperty('causes', []);
}
constructor(message, ...causes) {
super(message);
this.defineHiddenProperty('causes', causes);
}
}
module.exports = TraceError;

@@ -0,5 +1,21 @@

'use strict';
var TraceError = require('../');
var assert = require('assert');
var fs = require('fs');
var path = require('path');
describe('TraceError', function () {
it('should be able to access the properties via. toJSON', function () {
var err = new TraceError('sup');
assert.deepEqual(Object.keys(err.toJSON()).sort(), ['stack', 'name', 'message'].sort());
TraceError.Exception.searchPrototype = true;
assert.deepEqual(Object.keys(err.toJSON()).sort(), ['stack', 'name', 'message'].sort());
TraceError.Exception.searchPrototype = false;
});
it('should assign the constructor name', function () {
assert.equal(new TraceError('sup').name, 'TraceError');
});
it('should chain multiple errors across different levels', function () {

@@ -13,9 +29,125 @@ try {

} catch (e) {
assert.deepEqual(e.messages(), ['Captured', {test: 5}, 'Test error', 'Test cause', {error: 'test'}]);
assert.equal(e.message, 'Captured');
assert.equal(e.cause().test, 5);
assert.equal(e.causes()[1].message, 'Test error');
assert.equal(e.causes()[1].cause().message, 'Test cause');
assert.equal(e.causes()[1].causes()[1].error, 'test');
assert.equal(e.cause(1).message, 'Test error');
assert.equal(e.cause(1).cause().message, 'Test cause');
assert.equal(e.cause(1).cause(1).error, 'test');
}
});
});
it('should show type info', function () {
assert.equal(new TraceError() instanceof TraceError, true);
assert.equal(new TraceError() instanceof TraceError.Exception, true);
assert.equal(new TraceError() instanceof Error, true);
});
it('should use a custom stack by modifying Error prototype', function () {
Object.defineProperty(Error.prototype, 'customStack', {
configurable: true,
get: function () {
return this.message;
}
});
TraceError.globalStackProperty = 'customStack';
try {
try {
throw new TraceError('Test error', Error('Test cause'), {error: 'test'});
} catch (e) {
throw new TraceError('Captured', {test: 5}, e);
}
} catch (e) {
assert.equal(e.stack, fs.readFileSync(path.join(__dirname, 'custom-stack-1.txt'), 'utf8'));
}
});
it('should use a custom stack by modifying Error prototype; should not cause stack overflow', function () {
Object.defineProperty(Error.prototype, 'customStack', {
configurable: true,
get: function () {
return this.stack.split('\n')[0];
}
});
TraceError.globalStackProperty = 'customStack';
try {
try {
throw new TraceError('Test error', Error('Test cause'), {error: 'test'});
} catch (e) {
throw new TraceError('Captured', {test: 5}, e);
}
} catch (e) {
assert.equal(e.stack, fs.readFileSync(path.join(__dirname, 'custom-stack-2.txt'), 'utf8'));
}
// restore
TraceError.globalStackProperty = 'stack';
});
it('should extend TraceError using classical inheritance and modify the stack appropriately', function () {
function MyError() {
TraceError.apply(this, arguments);
}
MyError.prototype = Object.create(TraceError.prototype);
MyError.prototype.constructor = MyError;
Object.defineProperty(MyError.prototype, 'stack', {
get: function () {
return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(MyError.prototype), 'stack')
.get
.call(this)
.split('\n')[0];
}
});
assert.equal(new MyError() instanceof MyError, true);
assert.equal(new MyError('Cat dog').name, 'MyError');
assert.equal(new MyError('lol').stack, 'MyError: lol');
});
it('should extend TraceError using classical inheritance and modify the stack with custom stack', function () {
Object.defineProperty(Error.prototype, 'customStack', {
configurable: true,
get: function () {
return 'YoloCat';
}
});
function CodeError(code) {
TraceError.apply(this, arguments);
// add a code property
this.defineHiddenProperty('code', code);
}
CodeError.prototype = Object.create(TraceError.prototype);
CodeError.prototype.constructor = CodeError;
CodeError.prototype.code = function () {
return this.getHiddenProperty('code');
};
Object.defineProperty(CodeError.prototype, 'stack', {
get: function () {
return this.code() + ': ' +
Object.getOwnPropertyDescriptor(Object.getPrototypeOf(CodeError.prototype), 'stack')
.get
.call(this)
.split('\n')[0];
}
});
TraceError.globalStackProperty = 'customStack';
assert.equal(new CodeError() instanceof CodeError, true);
assert.equal(new CodeError('Cat dog').name, 'CodeError');
assert.equal(new CodeError('lol').stack, 'lol: YoloCat');
assert.equal(new CodeError('lol').customStack, 'YoloCat');
TraceError.globalStackProperty = 'stack';
});
});
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc