UNPKG

error-to-json

Version:

Returns a JSON representation of an error (handles nested errors and calls nested toJSONs)

56 lines 1.84 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.parse = void 0; const fast_safe_stringify_1 = __importDefault(require("fast-safe-stringify")); exports.default = errToJSON; const nonEnumerablePropsToCopy = ['code', 'errno', 'syscall']; function errToJSON(err) { let json; // @ts-ignore if (typeof err.toJSON === 'function') { // @ts-ignore json = err.toJSON(); } else { // stub error tojson const stubbed = 'toJSON' in Error.prototype; // @ts-ignore const toJSON = Error.prototype.toJSON; // @ts-ignore Error.prototype.toJSON = function () { const json = Object.assign(Object.assign({}, this), { // normal props name: this.name, message: this.message, stack: this.stack }); nonEnumerablePropsToCopy.forEach((key) => { // @ts-ignore if (key in this) json[key] = this[key]; }); return JSON.parse(fast_safe_stringify_1.default(json)); }; // get error json // @ts-ignore json = err.toJSON(); // unstub error tojson // @ts-ignore if (stubbed) Error.prototype.toJSON = toJSON; } // return error json return json; } function parse(json) { const err = new Error(json.message); const stack = err.stack || ''; Object.assign(err, json); if (err.stack === stack) { // remove stacktrace generated by error constructor above err.stack = stack.slice(0, stack.indexOf('\n')); } return err; } exports.parse = parse; //# sourceMappingURL=index.js.map