PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/error/error.go

https://github.com/davdunc/etcd
Go | 90 lines | 51 code | 17 blank | 22 comment | 3 complexity | 672882373a51c1f12bd29ab76526cf77 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause, CC0-1.0
  1. /*
  2. Copyright 2013 CoreOS Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package error
  14. import (
  15. "encoding/json"
  16. "net/http"
  17. )
  18. var errors map[int]string
  19. const ()
  20. func init() {
  21. errors = make(map[int]string)
  22. // command related errors
  23. errors[100] = "Key Not Found"
  24. errors[101] = "The given PrevValue is not equal to the value of the key"
  25. errors[102] = "Not A File"
  26. errors[103] = "Reached the max number of machines in the cluster"
  27. // Post form related errors
  28. errors[200] = "Value is Required in POST form"
  29. errors[201] = "PrevValue is Required in POST form"
  30. errors[202] = "The given TTL in POST form is not a number"
  31. errors[203] = "The given index in POST form is not a number"
  32. // raft related errors
  33. errors[300] = "Raft Internal Error"
  34. errors[301] = "During Leader Election"
  35. // keyword
  36. errors[400] = "The prefix of the given key is a keyword in etcd"
  37. // etcd related errors
  38. errors[500] = "watcher is cleared due to etcd recovery"
  39. }
  40. type Error struct {
  41. ErrorCode int `json:"errorCode"`
  42. Message string `json:"message"`
  43. Cause string `json:"cause,omitempty"`
  44. }
  45. func NewError(errorCode int, cause string) Error {
  46. return Error{
  47. ErrorCode: errorCode,
  48. Message: errors[errorCode],
  49. Cause: cause,
  50. }
  51. }
  52. func Message(code int) string {
  53. return errors[code]
  54. }
  55. // Only for error interface
  56. func (e Error) Error() string {
  57. return e.Message
  58. }
  59. func (e Error) toJsonString() string {
  60. b, _ := json.Marshal(e)
  61. return string(b)
  62. }
  63. func (e Error) Write(w http.ResponseWriter) {
  64. // 3xx is reft internal error
  65. if e.ErrorCode/100 == 3 {
  66. http.Error(w, e.toJsonString(), http.StatusInternalServerError)
  67. } else {
  68. http.Error(w, e.toJsonString(), http.StatusBadRequest)
  69. }
  70. }