Let's say I have some code like this:
value, err := some3rdpartylib.DoSomething() if err != nil { panic(err) }
In case err != nil
I will get something like this:
panic: some error explanation here goroutine 1 [running]: main.main() /tmp/blabla/main.go:6 +0x80
This stack trace is completely legit but sometimes these error messages may not clarify what happened and so I'd like to dig deeper into the source code of the 3rd party library to investigate what exactly causes this error to be returned. However when my code panics like this, there is no way to get the actual place that returned this error.
A little bit more clarification: as I'm coming from JVM world where exceptions are thrown I can completely trace what exactly line of code thrown the exception and thus can easily find the place and see what gone wrong. Go stack trace ends exactly where my code panics and thus not too useful in my case.
I've created a playground here and ideally I'd like to be able to trace the error to the place it was actually returned from, not panic. (e.g. to line 17, return "", errors.New("some error explanation here")
)
Is this even possible?
Answer: A Stack Trace Error gives the location of the error within the program. The actual error message is listed in BOLD. Use the actual error messages to search the Knowledgebase or to report to Customer Support.
To read this stack trace, start at the top with the Exception's type - ArithmeticException and message The denominator must not be zero . This gives an idea of what went wrong, but to discover what code caused the Exception, skip down the stack trace looking for something in the package com.
In simple terms, a stack trace is a list of the method calls that the application was in the middle of when an Exception was thrown. Simple Example. With the example given in the question, we can determine exactly where the exception was thrown in the application.
I think that there is an easier way to achieve this. You can try wrapping errors using the golang "default" third party library error package:
You need to define the interface to be implemented by your error
:
type stackTracer interface { StackTrace() errors.StackTrace }
Then use it when wrapping/processing an error :
err, ok := errors.(stackTracer) // ok is false if errors doesn't implement stackTracer stack := err.StackTrace() fmt.Println(stack) // here you'll have your stack trace
Shortly: this is not possible. Since errors are values, they are not treated in any special way. Due to this, when function (normally) returns, stack is no more available (ie. another function call may overwrite memory used by returning-error function' stack).
There is a tool called trace which was introduced with go1.5, but for now, there is no comprehensive tutorial available neither any of those I found says that this kind of feature will be included.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With