error.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. "fmt"
  19. "log"
  20. "github.com/pkg/errors"
  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.Errorf("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", errors.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 errors.Wrap(err, msg)
  54. }
  55. // Wrapf is Wrap with extra info.
  56. func Wrapf(err error, format string, args ...interface{}) error {
  57. if !debugMode {
  58. if err == nil {
  59. return nil
  60. }
  61. return fmt.Errorf(format+" error: %+v", append(args, err)...)
  62. }
  63. return errors.Wrapf(err, format, args...)
  64. }
  65. func CombineErrors(one, other error) error {
  66. if one != nil && other != nil {
  67. return fmt.Errorf("%v; %v", one, other)
  68. }
  69. if one != nil && other == nil {
  70. return fmt.Errorf("%v", one)
  71. }
  72. if one == nil && other != nil {
  73. return fmt.Errorf("%v", other)
  74. }
  75. return nil
  76. }