2

How do I get the stacktrace from an Exception object? I am specifically looking to extract the call stack and line numbers, given an Exception.

I tried this:


function do_it(int $x, int $y): void {
  try {
    $result = $x / $y;
  }

  catch (\Exception $ex) {
    echo "Caught an Exception\n";
    $ex::getTrace();
  }
}

<<__EntryPoint>>
function main(): void {
  do_it(100, 0);
}

But I got as output:

Caught an Exception

Fatal error: Uncaught exception 'BadMethodCallException' with message 'Non-static method Exception::getTrace() cannot be called statically' in /Users/navyazaveri/hack_stuff/first.hack:9
Stack trace:
#0 /Users/navyazaveri/hack_stuff/first.hack(15): do_it()
#1 (): main()
#2 {main}
nz_21
  • 6,140
  • 7
  • 34
  • 80

1 Answers1

2

Exception::getTrace(), like in PHP, has an array of the stack trace details with file, line, function and args, except for the entrypoint which doesn't have line numbers or args (as of 4.42).

concat
  • 3,107
  • 16
  • 30
  • thanks, can you show me an example of this? I've edited my question with a tried example that does not work. – nz_21 Aug 13 '20 at 14:10
  • 1
    @nz_21 getTrace is an instance method, so just replace `::` in your example with `->`. – concat Aug 13 '20 at 14:17