gitlab.com/ignitionrobotics/web/ign-go@v1.0.0-rc4/errors/errors.go (about)

     1  package errors
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/pkg/errors"
     6  	"runtime"
     7  )
     8  
     9  // WithFunctionContext wraps an error with information about the function that generated the error.
    10  // `skip` is the number of stack frames that need to be removed to reach the function that generated the error. If this
    11  // function is called to wrap an error on the function that generated the error, then `skip` should be set to 1.
    12  // Higher values of `skip` are necessary to create error wrapping functions that make use of this function.
    13  func WithFunctionContext(err error, errMsg string, skip int) error {
    14  	// Get information about the function calling this function
    15  	pc, _, _, ok := runtime.Caller(skip)
    16  	if !ok {
    17  		return err
    18  	}
    19  	// Get the name of the function that generated the error
    20  	fn := runtime.FuncForPC(pc).Name()
    21  	// Prepare the error message
    22  	msg := fmt.Sprintf("(%s)", fn)
    23  	if errMsg != "" {
    24  		msg = fmt.Sprintf("(%s) %s", fn, errMsg)
    25  	}
    26  
    27  	return errors.Wrap(err, msg)
    28  }