errors.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "bytes"
  7. "fmt"
  8. )
  9. const (
  10. ErrorTypeInternal = 1 << iota
  11. ErrorTypeExternal = 1 << iota
  12. ErrorTypeAny = 0xffffffff
  13. )
  14. // Used internally to collect errors that occurred during an http request.
  15. type errorMsg struct {
  16. Error error `json:"error"`
  17. Flags int `json:"-"`
  18. Meta interface{} `json:"meta"`
  19. }
  20. type errorMsgs []errorMsg
  21. func (a errorMsgs) ByType(typ int) errorMsgs {
  22. if len(a) == 0 {
  23. return a
  24. }
  25. result := make(errorMsgs, 0, len(a))
  26. for _, msg := range a {
  27. if msg.Flags&typ > 0 {
  28. result = append(result, msg)
  29. }
  30. }
  31. return result
  32. }
  33. func (a errorMsgs) Errors() []string {
  34. if len(a) == 0 {
  35. return []string{}
  36. }
  37. errorStrings := make([]string, len(a))
  38. for i, err := range a {
  39. errorStrings[i] = err.Error.Error()
  40. }
  41. return errorStrings
  42. }
  43. func (a errorMsgs) String() string {
  44. if len(a) == 0 {
  45. return ""
  46. }
  47. var buffer bytes.Buffer
  48. for i, msg := range a {
  49. fmt.Fprintf(&buffer, "Error #%02d: %s\n Meta: %v\n", (i + 1), msg.Error, msg.Meta)
  50. }
  51. return buffer.String()
  52. }