errors.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package domain
  2. import (
  3. "errors"
  4. "github.com/nicksnyder/go-i18n/v2/i18n"
  5. )
  6. type ErrorKind = string
  7. var NoError = i18n.Message{ID: "error.none", Other: "No error"}
  8. var Unimplemented = i18n.Message{ID: "error.unimplemented", Other: "Not yet implemented"}
  9. var ShortNotCreated = i18n.Message{ID: "short_not_created", Other: "Short URL not created for a new target"}
  10. var TargetInvalid = i18n.Message{ID: "error.target_invalid", Other: "Target invalid"}
  11. var ShortNotFound = i18n.Message{ID: "short_not_found", Other: "Short URL not defined"}
  12. var TargetBlocked = i18n.Message{ID: "target_blocked", Other: "Target blocked"}
  13. var TargetCensored = i18n.Message{ID: "target_censored", Other: "Target unavailable for legal reasons"}
  14. var StorageRead = i18n.Message{ID: "storage_read", Other: "Storage read error"}
  15. var StorageWrite = i18n.Message{ID: "storage_write", Other: "Storage write error"}
  16. var StorageUnspecified = i18n.Message{ID: "storage_unspecified", Other: "Storage unspecified error"}
  17. var ErrorMessages = map[ErrorKind]i18n.Message{
  18. NoError.ID: NoError,
  19. Unimplemented.ID: Unimplemented,
  20. ShortNotCreated.ID: ShortNotCreated,
  21. ShortNotFound.ID: ShortNotFound,
  22. TargetBlocked.ID: TargetBlocked,
  23. TargetCensored.ID: TargetCensored,
  24. StorageRead.ID: StorageRead,
  25. StorageWrite.ID: StorageWrite,
  26. StorageUnspecified.ID: StorageUnspecified,
  27. }
  28. // Error instances are created localized by MakeError(kind, detail, localizer),
  29. // so they do not need to support localization themselves.
  30. type Error struct {
  31. error
  32. Kind ErrorKind
  33. }
  34. // MakeError creates a localized error instance, ready to print.
  35. func MakeError(l *i18n.Localizer, kind ErrorKind, detail string) Error {
  36. format := i18n.Message{
  37. ID: "web.error.format",
  38. Description: "The format for errors",
  39. One: "{.Kind}: {.Detail}",
  40. }
  41. var message string
  42. if len(detail) == 0 {
  43. message = l.MustLocalize(&i18n.LocalizeConfig{
  44. MessageID: ErrorMessages[kind].ID,
  45. })
  46. } else {
  47. em, ok := ErrorMessages[kind]
  48. if !ok {
  49. em = i18n.Message{
  50. ID: "error.dynamic",
  51. Description: "This is an unplanned error generated on the fly from details. It should be replaced",
  52. }
  53. }
  54. localizedKind := l.MustLocalize(&i18n.LocalizeConfig{
  55. DefaultMessage: &em,
  56. MessageID: em.ID,
  57. })
  58. message = l.MustLocalize(&i18n.LocalizeConfig{
  59. DefaultMessage: &format,
  60. TemplateData: map[string]string{
  61. "Kind": localizedKind,
  62. "Detail": detail,
  63. },
  64. })
  65. }
  66. return Error{
  67. Kind: kind,
  68. error: errors.New(message),
  69. }
  70. }