error.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright 2017 Dgraph Labs, Inc. and Contributors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package y
  17. // This file contains some functions for error handling. Note that we are moving
  18. // towards using x.Trace, i.e., rpc tracing using net/tracer. But for now, these
  19. // functions are useful for simple checks logged on one machine.
  20. // Some common use cases are:
  21. // (1) You receive an error from external lib, and would like to check/log fatal.
  22. // For this, use x.Check, x.Checkf. These will check for err != nil, which is
  23. // more common in Go. If you want to check for boolean being true, use
  24. // x.Assert, x.Assertf.
  25. // (2) You receive an error from external lib, and would like to pass on with some
  26. // stack trace information. In this case, use x.Wrap or x.Wrapf.
  27. // (3) You want to generate a new error with stack trace info. Use x.Errorf.
  28. import (
  29. "fmt"
  30. "log"
  31. "github.com/pkg/errors"
  32. )
  33. var debugMode = true
  34. // Check logs fatal if err != nil.
  35. func Check(err error) {
  36. if err != nil {
  37. log.Fatalf("%+v", Wrap(err))
  38. }
  39. }
  40. // Check2 acts as convenience wrapper around Check, using the 2nd argument as error.
  41. func Check2(_ interface{}, err error) {
  42. Check(err)
  43. }
  44. // AssertTrue asserts that b is true. Otherwise, it would log fatal.
  45. func AssertTrue(b bool) {
  46. if !b {
  47. log.Fatalf("%+v", errors.Errorf("Assert failed"))
  48. }
  49. }
  50. // AssertTruef is AssertTrue with extra info.
  51. func AssertTruef(b bool, format string, args ...interface{}) {
  52. if !b {
  53. log.Fatalf("%+v", errors.Errorf(format, args...))
  54. }
  55. }
  56. // Wrap wraps errors from external lib.
  57. func Wrap(err error) error {
  58. if !debugMode {
  59. return err
  60. }
  61. return errors.Wrap(err, "")
  62. }
  63. // Wrapf is Wrap with extra info.
  64. func Wrapf(err error, format string, args ...interface{}) error {
  65. if !debugMode {
  66. if err == nil {
  67. return nil
  68. }
  69. return fmt.Errorf(format+" error: %+v", append(args, err)...)
  70. }
  71. return errors.Wrapf(err, format, args...)
  72. }