Search code examples
hacklang

Hacklang: how to get stacktrace from Exception?


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}

Solution

  • 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).