Errors stacktrace example ("Concurrency in Go" pag 151)


(J Ohn Stuart) #1

In the book “Concurrency in Go” pag 151 there is this example of a method that wraps an error into another data type called MyError (a well formated error).

func wrapError(err error, messagef string, msgArgs … interface{}) MyError {
return MyError{
Inner: error,
Message: fmt.Sprintf(messagef, msgArgs),
StackTrace: string(debug.Stack()) <- what is he doing here ?

}
}

Why is she(author is female) putting the current value of debug.Stack() ? Does she assume that this method will be called just after an error occurs ?

What does debug.Stack() do ? Please clarify.


(Curtis Allyn Green) #2

Appears the Author is wrapping the error with all of it’s relevant information to discover what happened. The debug.Stack() returns the entire stack trace of the running process:


(J Ohn Stuart) #3

The thing I fear is: an error occurs in a goroutine but by the time this wrapping method is called the stack trace of the running process will contain info from other goroutines launched by the same process. Is this a thing ? Is it reasonable to assume this will happen ?

P.S: thx for your reply!


(Curtis Allyn Green) #4

Stack returns a formatted stack trace of the goroutine that calls it. It calls runtime.Stack with a large enough buffer to capture the entire trace.

^-- From the docs, it’s designed to provide the stacktrace for whatever called it. If you wrap the error from the routine then there should never be a problem.