error.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. // Post form related errors
  16. errors[200] = "Value is Required in POST form"
  17. errors[201] = "PrevValue is Required in POST form"
  18. errors[202] = "The given TTL in POST form is not a number"
  19. errors[203] = "The given index in POST form is not a number"
  20. // raft related errors
  21. errors[300] = "Raft Internal Error"
  22. errors[301] = "During Leader Election"
  23. // keyword
  24. errors[400] = "The prefix of the given key is a keyword in etcd"
  25. // etcd related errors
  26. errors[500] = "watcher is cleared due to etcd recovery"
  27. }
  28. type Error struct {
  29. ErrorCode int `json:"errorCode"`
  30. Message string `json:"message"`
  31. Cause string `json:"cause,omitempty"`
  32. }
  33. func NewError(errorCode int, cause string) Error {
  34. return Error{
  35. ErrorCode: errorCode,
  36. Message: errors[errorCode],
  37. Cause: cause,
  38. }
  39. }
  40. func Message(code int) string {
  41. return errors[code]
  42. }
  43. // Only for error interface
  44. func (e Error) Error() string {
  45. return e.Message
  46. }
  47. func (e Error) toJsonString() string {
  48. b, _ := json.Marshal(e)
  49. return string(b)
  50. }
  51. func (e Error) Write(w http.ResponseWriter) {
  52. // 3xx is reft internal error
  53. if e.ErrorCode/100 == 3 {
  54. http.Error(w, e.toJsonString(), http.StatusInternalServerError)
  55. } else {
  56. http.Error(w, e.toJsonString(), http.StatusBadRequest)
  57. }
  58. }