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