...
1
18
19
20 package errors
21
22 import (
23 "encoding/json"
24 "io"
25 "net/http"
26 )
27
28 type ErrorReply struct {
29 Code int `json:"code,omitempty"`
30 Message string `json:"message,omitempty"`
31 }
32
33 const (
34 GenericError int = 1
35 DBError int = 2
36 GenericNotFoundError int = 3
37 InputNotValid int = 4
38
39 ConfigurationNotReady int = 100
40
41 DBDuplicateKey int = 11000
42 )
43
44 var errorMessages = map[int]string{
45 1: "Generic Error",
46 2: "DB Error",
47 3: "Not Found",
48 4: "Passed input is not correct or malformed",
49
50 100: "Configuration not ready",
51
52 11000: "A key is duplicated",
53 }
54
55 var errorStatus = map[int]int{
56 1: 500,
57 2: 500,
58 3: 404,
59 4: 400,
60
61 100: 500,
62
63 11000: 400,
64 }
65
66 func ReplyWithError(w http.ResponseWriter, errorCode int) {
67 w.WriteHeader(errorStatus[errorCode])
68 var errorReply = ErrorReply{Code: errorCode, Message: errorMessages[errorCode]}
69 errorReplyJSON, _ := json.Marshal(errorReply)
70 io.WriteString(w, string(errorReplyJSON))
71 }
72
73 func ReplyWithErrorMessage(w http.ResponseWriter, errorCode int, msg string) {
74 w.WriteHeader(errorStatus[errorCode])
75 var errorReply = ErrorReply{Code: errorCode, Message: msg}
76 errorReplyJSON, _ := json.Marshal(errorReply)
77 io.WriteString(w, string(errorReplyJSON))
78 }
79
View as plain text