-
Notifications
You must be signed in to change notification settings - Fork 9
/
ui.go
93 lines (82 loc) · 2.02 KB
/
ui.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
87
88
89
90
91
92
93
// Package httperrors ...
// CODE GENERATED AUTOMATICALLY
// DO NOT EDIT
package httperrors
import (
"context"
"encoding/json"
"net/http"
"strings"
"github.com/valyala/fasthttp"
)
type errorCode interface {
Error() string
StatusCode() int
}
type httpError struct {
Code int
Message string
}
// Error returns a text message corresponding to the given error.
func (e *httpError) Error() string {
return e.Message
}
// StatusCode returns an HTTP status code corresponding to the given error.
func (e *httpError) StatusCode() int {
return e.Code
}
type errorResponse struct {
Error bool `json:"error"`
ErrorText string `json:"errorText"`
AdditionalErrors map[string]string `json:"additionalErrors"`
Data *struct{} `json:"data"`
}
// ErrorProcessor ...
type ErrorProcessor struct {
defaultCode int
errors map[string]string
}
//Encode writes a svc error to the given http.ResponseWriter.
func (e *ErrorProcessor) Encode(ctx context.Context, r *fasthttp.Response, err error) {
errorText := err.Error()
if idx := strings.Index(err.Error(), ":"); idx != -1 {
numberOfError := err.Error()[:idx]
if text, ok := e.errors[numberOfError]; ok {
errorText = text
}
}
res := errorResponse{
Error: true,
ErrorText: errorText,
}
if er, ok := err.(errorCode); ok {
r.SetStatusCode(er.StatusCode())
} else {
r.SetStatusCode(e.defaultCode)
}
r.Header.Set("Content-Type", "application/json")
body, err := json.Marshal(res)
if err != nil {
return
}
r.SetBody(body)
}
// Decode reads a Service error from the given *http.Response.
func (e *ErrorProcessor) Decode(r *fasthttp.Response) error {
msgBytes := r.Body()
msg := strings.TrimSpace(string(msgBytes))
if msg == "" {
msg = http.StatusText(r.StatusCode())
}
return &httpError{
Code: r.StatusCode(),
Message: msg,
}
}
// NewErrorProcessor ...
func NewErrorProcessor(errors map[string]string) *ErrorProcessor {
return &ErrorProcessor{
defaultCode: http.StatusOK,
errors: errors,
}
}