frame.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xerrors
  5. import (
  6. "runtime"
  7. )
  8. // A Frame contains part of a call stack.
  9. type Frame struct {
  10. // Make room for three PCs: the one we were asked for, what it called,
  11. // and possibly a PC for skipPleaseUseCallersFrames. See:
  12. // https://go.googlesource.com/go/+/032678e0fb/src/runtime/extern.go#169
  13. frames [3]uintptr
  14. }
  15. // Caller returns a Frame that describes a frame on the caller's stack.
  16. // The argument skip is the number of frames to skip over.
  17. // Caller(0) returns the frame for the caller of Caller.
  18. func Caller(skip int) Frame {
  19. var s Frame
  20. runtime.Callers(skip+1, s.frames[:])
  21. return s
  22. }
  23. // location reports the file, line, and function of a frame.
  24. //
  25. // The returned function may be "" even if file and line are not.
  26. func (f Frame) location() (function, file string, line int) {
  27. frames := runtime.CallersFrames(f.frames[:])
  28. if _, ok := frames.Next(); !ok {
  29. return "", "", 0
  30. }
  31. fr, ok := frames.Next()
  32. if !ok {
  33. return "", "", 0
  34. }
  35. return fr.Function, fr.File, fr.Line
  36. }
  37. // Format prints the stack as error detail.
  38. // It should be called from an error's Format implementation
  39. // after printing any other error detail.
  40. func (f Frame) Format(p Printer) {
  41. if p.Detail() {
  42. function, file, line := f.location()
  43. if function != "" {
  44. p.Printf("%s\n ", function)
  45. }
  46. if file != "" {
  47. p.Printf("%s:%d\n", file, line)
  48. }
  49. }
  50. }