error.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package y
  6. // This file contains some functions for error handling. Note that we are moving
  7. // towards using x.Trace, i.e., rpc tracing using net/tracer. But for now, these
  8. // functions are useful for simple checks logged on one machine.
  9. // Some common use cases are:
  10. // (1) You receive an error from external lib, and would like to check/log fatal.
  11. // For this, use x.Check, x.Checkf. These will check for err != nil, which is
  12. // more common in Go. If you want to check for boolean being true, use
  13. // x.Assert, x.Assertf.
  14. // (2) You receive an error from external lib, and would like to pass on with some
  15. // stack trace information. In this case, use x.Wrap or x.Wrapf.
  16. // (3) You want to generate a new error with stack trace info. Use x.Errorf.
  17. import (
  18. "errors"
  19. "fmt"
  20. "log"
  21. )
  22. var debugMode = false
  23. // Check logs fatal if err != nil.
  24. func Check(err error) {
  25. if err != nil {
  26. log.Fatalf("%+v", Wrap(err, ""))
  27. }
  28. }
  29. // Check2 acts as convenience wrapper around Check, using the 2nd argument as error.
  30. func Check2(_ interface{}, err error) {
  31. Check(err)
  32. }
  33. // AssertTrue asserts that b is true. Otherwise, it would log fatal.
  34. func AssertTrue(b bool) {
  35. if !b {
  36. log.Fatalf("%+v", errors.New("Assert failed"))
  37. }
  38. }
  39. // AssertTruef is AssertTrue with extra info.
  40. func AssertTruef(b bool, format string, args ...interface{}) {
  41. if !b {
  42. log.Fatalf("%+v", fmt.Errorf(format, args...))
  43. }
  44. }
  45. // Wrap wraps errors from external lib.
  46. func Wrap(err error, msg string) error {
  47. if !debugMode {
  48. if err == nil {
  49. return nil
  50. }
  51. return fmt.Errorf("%s err: %+v", msg, err)
  52. }
  53. return fmt.Errorf("%s: %w", msg, err)
  54. }
  55. // Wrapf is Wrap with extra info.
  56. func Wrapf(err error, format string, args ...interface{}) error {
  57. return Wrap(err, fmt.Sprintf(format, args...))
  58. }
  59. func CombineErrors(one, other error) error {
  60. if one != nil && other != nil {
  61. return fmt.Errorf("%v; %v", one, other)
  62. }
  63. if one != nil && other == nil {
  64. return fmt.Errorf("%v", one)
  65. }
  66. if one == nil && other != nil {
  67. return fmt.Errorf("%v", other)
  68. }
  69. return nil
  70. }