forked from netlify/gocommerce
/
errors.go
71 lines (59 loc) · 1.57 KB
/
errors.go
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
package api
import (
"fmt"
"net/http"
"sync"
)
func badRequestError(w http.ResponseWriter, fmtString string, args ...interface{}) *HTTPError {
err := httpError(400, fmtString, args...)
sendJSON(w, err.Code, err)
return err
}
func unprocessableEntity(w http.ResponseWriter, fmtString string, args ...interface{}) *HTTPError {
err := httpError(422, fmtString, args...)
sendJSON(w, err.Code, err)
return err
}
func internalServerError(w http.ResponseWriter, fmtString string, args ...interface{}) *HTTPError {
err := httpError(500, fmtString, args...)
sendJSON(w, err.Code, err)
return err
}
func notFoundError(w http.ResponseWriter, fmtString string, args ...interface{}) *HTTPError {
err := httpError(404, fmtString, args...)
sendJSON(w, err.Code, err)
return err
}
func unauthorizedError(w http.ResponseWriter, fmtString string, args ...interface{}) *HTTPError {
err := httpError(401, fmtString, args...)
sendJSON(w, err.Code, err)
return err
}
// HTTPError is an error with a message
type HTTPError struct {
Code int `json:"code"`
Message string `json:"msg"`
}
func (e HTTPError) Error() string {
return fmt.Sprintf("%d: %s", e.Code, e.Message)
}
func httpError(code int, fmtString string, args ...interface{}) *HTTPError {
return &HTTPError{
Code: code,
Message: fmt.Sprintf(fmtString, args...),
}
}
type sharedError struct {
err error
mutex sync.Mutex
}
func (e *sharedError) setError(err error) {
e.mutex.Lock()
e.err = err
e.mutex.Unlock()
}
func (e *sharedError) hasError() bool {
e.mutex.Lock()
defer e.mutex.Unlock()
return e.err != nil
}