errors.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) 2019, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. /*
  20. Package errors provides error wrapping helpers that add inline, single frame
  21. stack trace information to error messages.
  22. */
  23. package errors
  24. import (
  25. "fmt"
  26. "runtime"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/stacktrace"
  28. )
  29. // TraceNew returns a new error with the given message, wrapped with the caller
  30. // stack frame information.
  31. func TraceNew(message string) error {
  32. err := fmt.Errorf("%s", message)
  33. pc, _, line, _ := runtime.Caller(1)
  34. return fmt.Errorf("%s#%d: %w", stacktrace.GetFunctionName(pc), line, err)
  35. }
  36. // Tracef returns a new error with the given formatted message, wrapped with
  37. // the caller stack frame information.
  38. func Tracef(format string, args ...interface{}) error {
  39. err := fmt.Errorf(format, args...)
  40. pc, _, line, _ := runtime.Caller(1)
  41. return fmt.Errorf("%s#%d: %w", stacktrace.GetFunctionName(pc), line, err)
  42. }
  43. // Trace wraps the given error with the caller stack frame information.
  44. func Trace(err error) error {
  45. if err == nil {
  46. return nil
  47. }
  48. pc, _, line, _ := runtime.Caller(1)
  49. return fmt.Errorf("%s#%d: %w", stacktrace.GetFunctionName(pc), line, err)
  50. }
  51. // TraceMsg wraps the given error with the caller stack frame information
  52. // and the given message.
  53. func TraceMsg(err error, message string) error {
  54. if err == nil {
  55. return nil
  56. }
  57. pc, _, line, _ := runtime.Caller(1)
  58. return fmt.Errorf("%s#%d: %s: %w", stacktrace.GetFunctionName(pc), line, message, err)
  59. }