-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
81 lines (68 loc) · 1.72 KB
/
Copy patherrors.go
File metadata and controls
81 lines (68 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"errors"
"fmt"
"net/http"
)
var (
errAuthInvalid = &authError{msg: "wrong credentials, try again"}
errAuthMissing = &authError{msg: "authorization required"}
errAuthTokenType = &authError{msg: "invalid token type"}
errUnauthorized = errors.New("operation is not authorized")
errVoteRejected = errors.New("vote rejected")
errSessionClosed = errors.New("session closed")
errSessionOpen = errors.New("session is already open")
)
type authError struct {
msg string
}
func (e *authError) Error() string {
return e.msg
}
// systemError is an error used by API handlers
type systemError struct {
err error
msg string
}
type errClientError struct {
msg string
}
func (e *errClientError) Error() string {
return e.msg
}
func (se *systemError) Error() string {
return se.msg
}
func writeAPIError(w http.ResponseWriter, err error) {
switch v := err.(type) {
case *authError:
http.Error(w, v.Error(), http.StatusUnauthorized)
return
case *errClientError:
writeJSONError(w, http.StatusBadRequest, err)
return
}
switch err {
case errUnauthorized:
http.Error(w, err.Error(), http.StatusForbidden)
case errVoteRejected:
fallthrough
case errSessionOpen:
fallthrough
case errSessionClosed:
writeJSONError(w, http.StatusBadRequest, err)
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func writeJSONError(w http.ResponseWriter, statusCode int, err error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
w.Write([]byte(fmt.Sprintf("{\"error\": \"%s\"}", err.Error())))
}
func newClientError(msg string) *errClientError {
return &errClientError{msg: msg}
}
func newSystemError(msg string) *systemError {
return &systemError{msg: msg}
}