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

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.

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:

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!

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.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.