Try catch ex.stack 只获取第一行

Try catch ex.stack get first line only

如何只获取 console.log(ex.stack)>

的第一行

例如我只想要这个:

TypeError: Object #<Object> has no method 'debug'

其中:

TypeError: Object #<Object> has no method 'debug'
    at eval at <anonymous> (unknown source)
    at eval (native)
    at Object._evaluateOn (unknown source)
    at Object._evaluateAndWrap (unknown source)
    at Object.evaluate (unknown source)

想要错误信息,直接抓取即可。不需要从完整的堆栈跟踪中解析出来:

var Object = {};
try {
  Object.debug();
} catch(ex) {
  console.log(ex.message);
}

如果出于某种原因这不可能,则堆栈跟踪似乎只是一个字符串:

console.log(typeof ex.stack);

string

...所以选择你最喜欢的字符串操作技术:

var Object = {};
try {
  Object.debug();
} catch(ex) {
  console.log(ex.stack.split("\n", 1).join(""));
}