5

There's the getStackTrace() function that gets stack trace from the current exception.

But it doesn't work for specific exception, this code won't work error.getStackTrace()

I need it for log function

proc error*(message: string, exception: Exception): void =
    stderr.write_line fmt"      {message}"
    stderr.write_line exception.getStackTrace()
Alex Craft
  • 13,598
  • 11
  • 69
  • 133

1 Answers1

4

Your sample code does not even compile for me, since getCurrentException returns a reference to an Exception and not a copy of it so there's no way to pass it to error(). Here's a full sample that compiles for me:

proc failHard() =
    doAssert toInt(1.49) == 0

proc error*(message: string, exception: ref Exception) =
    echo message
    echo exception.getStackTrace()

proc main() =
    try: failHard()
    except: error("oops", getCurrentException())

main()

When I compile and run this program I get the following output:

$ ./t
oops
/private/tmp/t/t.nim(12) t
/private/tmp/t/t.nim(9)  main
/private/tmp/t/t.nim(2)  failHard
/Users/gradha/.choosenim/toolchains/nim-1.2.6/lib/system/assertions.nim(29) failedAssertImpl
/Users/gradha/.choosenim/toolchains/nim-1.2.6/lib/system/assertions.nim(22) raiseAssert
/Users/gradha/.choosenim/toolchains/nim-1.2.6/lib/system/fatal.nim(49) sysFatal

Note that getStackTrace() documentation mentions it does not offer much information in non debug builds:

$ nim c -d:release -r t.nim 
Hint: used config file '/Users/gradha/.choosenim/toolchains/nim-1.2.6/config/nim.cfg' [Conf]
Hint: 320 LOC; 0.096 sec; 5.379MiB peakmem; Release build; proj: /private/tmp/t/t.nim; out: /private/tmp/t/t [SuccessX]
Hint: /private/tmp/t/t  [Exec]
oops
fatal.nim(49)            sysFatal
Grzegorz Adam Hankiewicz
  • 7,349
  • 1
  • 36
  • 78