error.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Package krberror provides error type and functions for gokrb5.
  2. package krberror
  3. import (
  4. "fmt"
  5. "strings"
  6. )
  7. // Error type descriptions.
  8. const (
  9. separator = " < "
  10. EncodingError = "Encoding_Error"
  11. NetworkingError = "Networking_Error"
  12. DecryptingError = "Decrypting_Error"
  13. EncryptingError = "Encrypting_Error"
  14. ChksumError = "Checksum_Error"
  15. KRBMsgError = "KRBMessage_Handling_Error"
  16. ConfigError = "Configuration_Error"
  17. )
  18. // Krberror is an error type for gokrb5
  19. type Krberror struct {
  20. RootCause string
  21. EText []string
  22. }
  23. // Error function to implement the error interface.
  24. func (e Krberror) Error() string {
  25. return fmt.Sprintf("[Root cause: %s] ", e.RootCause) + strings.Join(e.EText, separator)
  26. }
  27. // Add another error statement to the error.
  28. func (e *Krberror) Add(et string, s string) {
  29. e.EText = append([]string{fmt.Sprintf("%s: %s", et, s)}, e.EText...)
  30. }
  31. // NewKrberror creates a new instance of Krberror.
  32. func NewKrberror(et, s string) Krberror {
  33. return Krberror{
  34. RootCause: et,
  35. EText: []string{s},
  36. }
  37. }
  38. // Errorf appends to or creates a new Krberror.
  39. func Errorf(err error, et, format string, a ...interface{}) Krberror {
  40. if e, ok := err.(Krberror); ok {
  41. if len(a) > 0 {
  42. e.EText = append([]string{fmt.Sprintf("%s: "+format, et, a)}, e.EText...)
  43. return e
  44. }
  45. e.EText = append([]string{fmt.Sprintf("%s: "+format, et)}, e.EText...)
  46. return e
  47. }
  48. if len(a) > 0 {
  49. return NewErrorf(et, format+": %s", a, err)
  50. }
  51. return NewErrorf(et, format+": %s", err)
  52. }
  53. // NewErrorf creates a new Krberror from a formatted string.
  54. func NewErrorf(et, format string, a ...interface{}) Krberror {
  55. var s string
  56. if len(a) > 0 {
  57. s = fmt.Sprintf("%s: %s", et, fmt.Sprintf(format, a...))
  58. } else {
  59. s = fmt.Sprintf("%s: %s", et, format)
  60. }
  61. return Krberror{
  62. RootCause: et,
  63. EText: []string{s},
  64. }
  65. }