nodejs global的妙用

//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)

 

nodejs 优雅的抛出异常

//ctx.js
let ctx = {};
ctx.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 = ctx;
//test.js
const ctx = require('./ctx.js');

try {
    throw ctx.error("test", 500);
} catch (e) {
    console.log(e.message, e.code, e.file);
}
test 500 at Object.<anonymous> (F:\jy\jkpt_backend\local_test\t_error.js:9:20)