//gctx.js
//gctx.js /** * global context * @type {{}} */ let gctx = {}; gctx.error = function(msg, code) { let error = (new Error); error.code = code; error.message = msg; error.file = error.stack.split('\n')[2]; return error; }; module.exports = gctx;
//subcall.js
let subcall = {}; subcall.call = function() { //调用全局报错 //减少重复性的引用 throw gctx.error('test', 500); }; module.exports = subcall;
//index.js
const gctx = require('./gctx.js'); const subcall = require('./subcall.js'); //引入全局global context global.gctx = gctx; try { // throw gctx.error('test', 500); subcall.call(); } catch (e) { console.log(e.message, e.code, e.file); }
输出:
test 500 at Object.subcall.call (....\local_test\subcall.js:4:14)