PageRenderTime 89ms CodeModel.GetById 14ms app.highlight 7ms RepoModel.GetById 64ms app.codeStats 0ms

/error/error.go

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