github.com/sandwich-go/boost@v1.3.29/xerror/xerror_stack.go (about)

     1  package xerror
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"runtime"
     7  )
     8  
     9  func (cc *Error) Caller(skip int) (file, funcName string, line int) {
    10  	if cc == nil {
    11  		return
    12  	}
    13  	for _, p := range cc.callStack {
    14  		if skip == 0 {
    15  			if fn := runtime.FuncForPC(p - 1); fn == nil {
    16  				funcName = "unknown"
    17  			} else {
    18  				funcName = fn.Name()
    19  				file, line = fn.FileLine(p - 1)
    20  			}
    21  			return
    22  		}
    23  		skip--
    24  	}
    25  	return
    26  }
    27  
    28  // Stack returns the stack callers as string.
    29  func (cc *Error) Stack() string {
    30  	if cc == nil {
    31  		return ""
    32  	}
    33  	var (
    34  		curr   = cc
    35  		index  = 1
    36  		buffer = bytes.NewBuffer(nil)
    37  	)
    38  	for curr != nil {
    39  		_, _ = buffer.WriteString(fmt.Sprintf("%d: %-v\n", index, curr))
    40  		index++
    41  		formatSubStack(curr.callStack, buffer)
    42  		if curr.err == nil {
    43  			break
    44  		}
    45  		if e, ok := curr.err.(*Error); ok {
    46  			curr = e
    47  		} else {
    48  			_, _ = buffer.WriteString(fmt.Sprintf("%d. %s\n", index, curr.err.Error()))
    49  			index++
    50  			break
    51  		}
    52  	}
    53  	return buffer.String()
    54  }