error.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package toml
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. "strconv"
  7. )
  8. var (
  9. errArrayMultiType = errors.New("array can't contain multiple types")
  10. )
  11. // LineError is returned by Unmarshal, UnmarshalTable and Parse
  12. // if the error is local to a line.
  13. type LineError struct {
  14. Line int
  15. StructField string
  16. Err error
  17. }
  18. func (err *LineError) Error() string {
  19. field := ""
  20. if err.StructField != "" {
  21. field = "(" + err.StructField + ") "
  22. }
  23. return fmt.Sprintf("line %d: %s%v", err.Line, field, err.Err)
  24. }
  25. func lineError(line int, err error) error {
  26. if err == nil {
  27. return nil
  28. }
  29. if _, ok := err.(*LineError); ok {
  30. return err
  31. }
  32. return &LineError{Line: line, Err: err}
  33. }
  34. func lineErrorField(line int, field string, err error) error {
  35. if lerr, ok := err.(*LineError); ok {
  36. return lerr
  37. } else if err != nil {
  38. err = &LineError{Line: line, StructField: field, Err: err}
  39. }
  40. return err
  41. }
  42. type overflowError struct {
  43. kind reflect.Kind
  44. v string
  45. }
  46. func (err *overflowError) Error() string {
  47. return fmt.Sprintf("value %s is out of range for %v", err.v, err.kind)
  48. }
  49. func convertNumError(kind reflect.Kind, err error) error {
  50. if numerr, ok := err.(*strconv.NumError); ok && numerr.Err == strconv.ErrRange {
  51. return &overflowError{kind, numerr.Num}
  52. }
  53. return err
  54. }
  55. type invalidUnmarshalError struct {
  56. typ reflect.Type
  57. }
  58. func (err *invalidUnmarshalError) Error() string {
  59. if err.typ == nil {
  60. return "toml: Unmarshal(nil)"
  61. }
  62. if err.typ.Kind() != reflect.Ptr {
  63. return "toml: Unmarshal(non-pointer " + err.typ.String() + ")"
  64. }
  65. return "toml: Unmarshal(nil " + err.typ.String() + ")"
  66. }
  67. type unmarshalTypeError struct {
  68. what string
  69. want string
  70. typ reflect.Type
  71. }
  72. func (err *unmarshalTypeError) Error() string {
  73. msg := fmt.Sprintf("cannot unmarshal TOML %s into %s", err.what, err.typ)
  74. if err.want != "" {
  75. msg += " (need " + err.want + ")"
  76. }
  77. return msg
  78. }
  79. type marshalNilError struct {
  80. typ reflect.Type
  81. }
  82. func (err *marshalNilError) Error() string {
  83. return fmt.Sprintf("toml: cannot marshal nil %s", err.typ)
  84. }
  85. type marshalTableError struct {
  86. typ reflect.Type
  87. }
  88. func (err *marshalTableError) Error() string {
  89. return fmt.Sprintf("toml: cannot marshal %s as table, want struct or map type", err.typ)
  90. }