errors.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2011 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 errors implements functions to manipulate errors.
  5. //
  6. // The New function creates errors whose only content is a text message.
  7. //
  8. // The Unwrap, Is and As functions work on errors that may wrap other errors.
  9. // An error wraps another error if its type has the method
  10. //
  11. // Unwrap() error
  12. //
  13. // If e.Unwrap() returns a non-nil error w, then we say that e wraps w.
  14. //
  15. // Unwrap unpacks wrapped errors. If its argument's type has an
  16. // Unwrap method, it calls the method once. Otherwise, it returns nil.
  17. //
  18. // A simple way to create wrapped errors is to call fmt.Errorf and apply the %w verb
  19. // to the error argument:
  20. //
  21. // errors.Unwrap(fmt.Errorf("... %w ...", ..., err, ...))
  22. //
  23. // returns err.
  24. //
  25. // Is unwraps its first argument sequentially looking for an error that matches the
  26. // second. It reports whether it finds a match. It should be used in preference to
  27. // simple equality checks:
  28. //
  29. // if errors.Is(err, fs.ErrExist)
  30. //
  31. // is preferable to
  32. //
  33. // if err == fs.ErrExist
  34. //
  35. // because the former will succeed if err wraps fs.ErrExist.
  36. //
  37. // As unwraps its first argument sequentially looking for an error that can be
  38. // assigned to its second argument, which must be a pointer. If it succeeds, it
  39. // performs the assignment and returns true. Otherwise, it returns false. The form
  40. //
  41. // var perr *fs.PathError
  42. // if errors.As(err, &perr) {
  43. // fmt.Println(perr.Path)
  44. // }
  45. //
  46. // is preferable to
  47. //
  48. // if perr, ok := err.(*fs.PathError); ok {
  49. // fmt.Println(perr.Path)
  50. // }
  51. //
  52. // because the former will succeed if err wraps an *fs.PathError.
  53. package errors
  54. // New returns an error that formats as the given text.
  55. // Each call to New returns a distinct error value even if the text is identical.
  56. func New(text string) error {
  57. return &errorString{text}
  58. }
  59. // errorString is a trivial implementation of error.
  60. type errorString struct {
  61. s string
  62. }
  63. func (e *errorString) Error() string {
  64. return e.s
  65. }