errors.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. ErrorTypePrivate = 1 << iota
  11. ErrorTypePublic = 1 << iota
  12. )
  13. const (
  14. ErrorMaskAny = 0xffffffff
  15. )
  16. // Used internally to collect errors that occurred during an http request.
  17. type errorMsg struct {
  18. Error error `json:"error"`
  19. Type int `json:"-"`
  20. Meta interface{} `json:"meta"`
  21. }
  22. type errorMsgs []errorMsg
  23. func (a errorMsgs) ByType(typ int) errorMsgs {
  24. if len(a) == 0 {
  25. return a
  26. }
  27. result := make(errorMsgs, 0, len(a))
  28. for _, msg := range a {
  29. if msg.Type&typ > 0 {
  30. result = append(result, msg)
  31. }
  32. }
  33. return result
  34. }
  35. func (a errorMsgs) Errors() []string {
  36. if len(a) == 0 {
  37. return []string{}
  38. }
  39. errors := make([]string, len(a))
  40. for i, err := range a {
  41. errors[i] = err.Error.Error()
  42. }
  43. return errors
  44. }
  45. func (a errorMsgs) String() string {
  46. if len(a) == 0 {
  47. return ""
  48. }
  49. var buffer bytes.Buffer
  50. for i, msg := range a {
  51. fmt.Fprintf(&buffer, "Error #%02d: %s\n Meta: %v\n", (i + 1), msg.Error, msg.Meta)
  52. }
  53. return buffer.String()
  54. }