显示javascript 的异常堆栈( show javascript exception stack)

访问量: 1161

refer to:  http://stackoverflow.com/questions/2923858/how-to-print-a-stack-trace-in-node-js and : http://stackoverflow.com/questions/147891/javascript-exception-stack-trace ( 比较有意思的是,这篇文章: http://massalabs.com/dev/2013/10/17/handling-errors-in-nodejs.html 对JS中的错误做了很详细的归类和说明...看晕我了. ^_^ @.@

我有两个文件

test_eval_exception.js :

fs = require('fs');
path = require('path');

file_path = path.join(__dirname, 'throw_error.js')
fs.readFile(file_path, { encoding: 'utf-8'},  function(error, data){
  eval(data)
})

throw_error.js:

a = 1;
b = 2;

c.a //throw error here

运行: ( 其实这个就足够了,可以看到 undefined: 4 , 说明是读取的文件的第四行出错)

$ node test_eval_exception.js 

undefined:4
c.a //throw error here
^
ReferenceError: c is not defined
    at eval (eval at  (/workspace/test_titanium/test_eval_exception.js:7:8), :4:1)
    at /workspace/test_titanium/test_eval_exception.js:7:3
    at fs.js:271:14
    at Object.oncomplete (fs.js:107:15)

我们也可以使用 try .. .catch: 

fs.readFile(file_path, { encoding: 'utf-8'},  function(error, data){
  try{
    eval(data)
  }catch(e){
    console.error(e.stack)
  }
})

结果:

ReferenceError: c is not defined
    at eval (eval at  (/workspace/happystock_titanium/test_eval_exception.js:9:10), :4:1)
    at /workspace/happystock_titanium/test_eval_exception.js:9:5
    at fs.js:271:14
    at Object.oncomplete (fs.js:107:15)

订阅/RSS Feed

Subscribe

分类/category