error.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package error
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. var errors map[int]string
  7. const ()
  8. func init() {
  9. errors = make(map[int]string)
  10. // command related errors
  11. errors[100] = "Key Not Found"
  12. errors[101] = "The given PrevValue is not equal to the value of the key"
  13. errors[102] = "Not A File"
  14. errors[103] = "Reached the max number of machines in the cluster"
  15. errors[104] = "Not A Directory"
  16. errors[105] = "Already exists"
  17. // Post form related errors
  18. errors[200] = "Value is Required in POST form"
  19. errors[201] = "PrevValue is Required in POST form"
  20. errors[202] = "The given TTL in POST form is not a number"
  21. errors[203] = "The given index in POST form is not a number"
  22. // raft related errors
  23. errors[300] = "Raft Internal Error"
  24. errors[301] = "During Leader Election"
  25. // keyword
  26. errors[400] = "The prefix of the given key is a keyword in etcd"
  27. // etcd related errors
  28. errors[500] = "watcher is cleared due to etcd recovery"
  29. }
  30. type Error struct {
  31. ErrorCode int `json:"errorCode"`
  32. Message string `json:"message"`
  33. Cause string `json:"cause,omitempty"`
  34. }
  35. func NewError(errorCode int, cause string) Error {
  36. return Error{
  37. ErrorCode: errorCode,
  38. Message: errors[errorCode],
  39. Cause: cause,
  40. }
  41. }
  42. func Message(code int) string {
  43. return errors[code]
  44. }
  45. // Only for error interface
  46. func (e Error) Error() string {
  47. return e.Message
  48. }
  49. func (e Error) toJsonString() string {
  50. b, _ := json.Marshal(e)
  51. return string(b)
  52. }
  53. func (e Error) Write(w http.ResponseWriter) {
  54. // 3xx is reft internal error
  55. if e.ErrorCode/100 == 3 {
  56. http.Error(w, e.toJsonString(), http.StatusInternalServerError)
  57. } else {
  58. http.Error(w, e.toJsonString(), http.StatusBadRequest)
  59. }
  60. }