errors.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package loader
  14. import (
  15. "fmt"
  16. "go/token"
  17. )
  18. // PositionedError represents some error with an associated position.
  19. // The position is tied to some external token.FileSet.
  20. type PositionedError struct {
  21. Pos token.Pos
  22. error
  23. }
  24. // Node is the intersection of go/ast.Node and go/types.Var.
  25. type Node interface {
  26. Pos() token.Pos // position of first character belonging to the node
  27. }
  28. // ErrFromNode returns the given error, with additional information
  29. // attaching it to the given AST node. It will automatically map
  30. // over error lists.
  31. func ErrFromNode(err error, node Node) error {
  32. if asList, isList := err.(ErrList); isList {
  33. resList := make(ErrList, len(asList))
  34. for i, baseErr := range asList {
  35. resList[i] = ErrFromNode(baseErr, node)
  36. }
  37. return resList
  38. }
  39. return PositionedError{
  40. Pos: node.Pos(),
  41. error: err,
  42. }
  43. }
  44. // MaybeErrList constructs an ErrList if the given list of
  45. // errors has any errors, otherwise returning nil.
  46. func MaybeErrList(errs []error) error {
  47. if len(errs) == 0 {
  48. return nil
  49. }
  50. return ErrList(errs)
  51. }
  52. // ErrList is a list of errors aggregated together into a single error.
  53. type ErrList []error
  54. func (l ErrList) Error() string {
  55. return fmt.Sprintf("%v", []error(l))
  56. }