error.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2017 Google Inc. All Rights Reserved.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package compiler
  15. // Error represents compiler errors and their location in the document.
  16. type Error struct {
  17. Context *Context
  18. Message string
  19. }
  20. // NewError creates an Error.
  21. func NewError(context *Context, message string) *Error {
  22. return &Error{Context: context, Message: message}
  23. }
  24. // Error returns the string value of an Error.
  25. func (err *Error) Error() string {
  26. if err.Context == nil {
  27. return "ERROR " + err.Message
  28. }
  29. return "ERROR " + err.Context.Description() + " " + err.Message
  30. }
  31. // ErrorGroup is a container for groups of Error values.
  32. type ErrorGroup struct {
  33. Errors []error
  34. }
  35. // NewErrorGroupOrNil returns a new ErrorGroup for a slice of errors or nil if the slice is empty.
  36. func NewErrorGroupOrNil(errors []error) error {
  37. if len(errors) == 0 {
  38. return nil
  39. } else if len(errors) == 1 {
  40. return errors[0]
  41. } else {
  42. return &ErrorGroup{Errors: errors}
  43. }
  44. }
  45. func (group *ErrorGroup) Error() string {
  46. result := ""
  47. for i, err := range group.Errors {
  48. if i > 0 {
  49. result += "\n"
  50. }
  51. result += err.Error()
  52. }
  53. return result
  54. }