errors.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package setting
  4. import (
  5. "errors"
  6. "tailscale.com/types/ptr"
  7. )
  8. var (
  9. // ErrNotConfigured is returned when the requested policy setting is not configured.
  10. ErrNotConfigured = errors.New("not configured")
  11. // ErrTypeMismatch is returned when there's a type mismatch between the actual type
  12. // of the setting value and the expected type.
  13. ErrTypeMismatch = errors.New("type mismatch")
  14. // ErrNoSuchKey is returned by [DefinitionOf] when no policy setting
  15. // has been registered with the specified key.
  16. //
  17. // Until 2024-08-02, this error was also returned by a [Handler] when the specified
  18. // key did not have a value set. While the package maintains compatibility with this
  19. // usage of ErrNoSuchKey, it is recommended to return [ErrNotConfigured] from newer
  20. // [source.Store] implementations.
  21. ErrNoSuchKey = errors.New("no such key")
  22. )
  23. // ErrorText represents an error that occurs when reading or parsing a policy setting.
  24. // This includes errors due to permissions issues, value type and format mismatches,
  25. // and other platform- or source-specific errors. It does not include
  26. // [ErrNotConfigured] and [ErrNoSuchKey], as those correspond to unconfigured
  27. // policy settings rather than settings that cannot be read or parsed
  28. // due to an error.
  29. //
  30. // ErrorText is used to marshal errors when a policy setting is sent over the wire,
  31. // allowing the error to be logged or displayed. It does not preserve the
  32. // type information of the underlying error.
  33. type ErrorText string
  34. // NewErrorText returns a [ErrorText] with the specified error message.
  35. func NewErrorText(text string) *ErrorText {
  36. return ptr.To(ErrorText(text))
  37. }
  38. // MaybeErrorText returns an [ErrorText] with the text of the specified error,
  39. // or nil if err is nil, [ErrNotConfigured], or [ErrNoSuchKey].
  40. func MaybeErrorText(err error) *ErrorText {
  41. if err == nil || errors.Is(err, ErrNotConfigured) || errors.Is(err, ErrNoSuchKey) {
  42. return nil
  43. }
  44. if err, ok := err.(*ErrorText); ok {
  45. return err
  46. }
  47. return ptr.To(ErrorText(err.Error()))
  48. }
  49. // Error implements error.
  50. func (e ErrorText) Error() string {
  51. return string(e)
  52. }
  53. // MarshalText implements [encoding.TextMarshaler].
  54. func (e ErrorText) MarshalText() (text []byte, err error) {
  55. return []byte(e.Error()), nil
  56. }
  57. // UnmarshalText implements [encoding.TextUnmarshaler].
  58. func (e *ErrorText) UnmarshalText(text []byte) error {
  59. *e = ErrorText(text)
  60. return nil
  61. }