-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
86 lines (71 loc) · 1.97 KB
/
error.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package apigatewayhttpapi
import (
"encoding/json"
"fmt"
"github.com/aws/aws-lambda-go/events"
"log"
"net/http"
"strconv"
)
func Error(statusCode int, opts ...Opt) events.APIGatewayV2HTTPResponse {
m := http.StatusText(statusCode)
if m == "" {
m = strconv.FormatInt(int64(statusCode), 10)
}
return ErrorWithMessage(statusCode, m, opts...)
}
func JSONError(statusCode int, opts ...Opt) events.APIGatewayV2HTTPResponse {
m := http.StatusText(statusCode)
if m == "" {
m = strconv.FormatInt(int64(statusCode), 10)
}
return JSONErrorWithMessage(statusCode, m, opts...)
}
func ErrorWithMessage(statusCode int, message string, opts ...Opt) events.APIGatewayV2HTTPResponse {
res := Errorf(statusCode, "%s", message)
for _, opt := range opts {
opt(&res)
}
return res
}
func JSONErrorWithMessage(statusCode int, message string, opts ...Opt) events.APIGatewayV2HTTPResponse {
res := JSONErrorf(statusCode, "%s", message)
for _, opt := range opts {
opt(&res)
}
return res
}
func Errorf(statusCode int, layout string, v ...interface{}) events.APIGatewayV2HTTPResponse {
m := fmt.Sprintf(layout, v...)
return events.APIGatewayV2HTTPResponse{
StatusCode: statusCode,
Headers: map[string]string{"Content-Type": "text/plain"},
Body: m,
}
}
func JSONErrorf(statusCode int, layout string, v ...interface{}) events.APIGatewayV2HTTPResponse {
t := http.StatusText(statusCode)
if t == "" {
t = strconv.FormatInt(int64(statusCode), 10)
}
m := fmt.Sprintf(layout, v...)
e := struct {
Status int `json:"status"`
Type string `json:"type,omitempty"`
Message string `json:"message,omitempty"`
}{
Status: statusCode,
Type: t,
Message: m,
}
data, err := json.Marshal(e)
if err != nil {
log.Printf("ERROR marshal error response body")
return Errorf(statusCode, layout, v...)
}
return events.APIGatewayV2HTTPResponse{
StatusCode: statusCode,
Headers: map[string]string{"Content-Type": "application/json"},
Body: string(data),
}
}