admin管理员组

文章数量:1332872

How do I get the first line only of a console.log(ex.stack)>

For example I only want this:

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

Out of this:

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)

How do I get the first line only of a console.log(ex.stack)>

For example I only want this:

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

Out of this:

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)
Share Improve this question asked Jun 14, 2016 at 15:18 HarryHarry 55k76 gold badges186 silver badges270 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

If you want the error message, just grab it directly. There's no need to parse it out from the full stack trace:

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

If that's not possible for whatever the reason, the stack trace appears to be nothing but a string:

console.log(typeof ex.stack);

string

... so pick your favourite string manipulation technique:

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

本文标签: javascriptTry catch exstack get first line onlyStack Overflow