forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_error.go
194 lines (158 loc) · 4.44 KB
/
handler_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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package main
import (
"bytes"
"encoding/base64"
"fmt"
"net/http"
"runtime/pprof"
"strconv"
"strings"
"time"
)
const (
defaultTemplateName = "error"
defaultTemplateFormat = "json"
defaultContentType = "application/json"
)
// APIError is generic error object returned if there is something wrong with the request
type APIError struct {
Message string
}
// ErrorHandler is invoked whenever there is an issue with a proxied request, most middleware will invoke
// the ErrorHandler if something is wrong with the request and halt the request processing through the chain
type ErrorHandler struct {
*TykMiddleware
}
// HandleError is the actual error handler and will store the error details in analytics if analytics processing is enabled.
func (e *ErrorHandler) HandleError(w http.ResponseWriter, r *http.Request, errMsg string, errCode int) {
var templateExtension string
var contentType string
switch r.Header.Get("Content-Type") {
case "application/xml":
templateExtension = "xml"
contentType = "application/xml"
default:
templateExtension = "json"
contentType = "application/json"
}
w.Header().Set("Content-Type", contentType)
templateName := fmt.Sprintf("error_%s.%s", strconv.Itoa(errCode), templateExtension)
// Try to use an error template that matches the HTTP error code and the content type: 500.json, 400.xml, etc.
tmpl := templates.Lookup(templateName)
// Fallback to a generic error template, but match the content type: error.json, error.xml, etc.
if tmpl == nil {
templateName = fmt.Sprintf("%s.%s", defaultTemplateName, templateExtension)
tmpl = templates.Lookup(templateName)
}
// If no template is available for this content type, fallback to "error.json".
if tmpl == nil {
templateName = fmt.Sprintf("%s.%s", defaultTemplateName, defaultTemplateFormat)
tmpl = templates.Lookup(templateName)
w.Header().Set("Content-Type", defaultContentType)
}
// Need to return the correct error code!
w.WriteHeader(errCode)
apiError := APIError{errMsg}
tmpl.Execute(w, &apiError)
if memProfFile != nil {
pprof.WriteHeapProfile(memProfFile)
}
if e.Spec.DoNotTrack {
return
}
// Track the key ID if it exists
token := ctxGetAuthToken(r)
var alias string
if config.StoreAnalytics(r) {
t := time.Now()
version := e.Spec.getVersionFromRequest(r)
if version == "" {
version = "Non Versioned"
}
if e.Spec.Proxy.StripListenPath {
r.URL.Path = strings.Replace(r.URL.Path, e.Spec.Proxy.ListenPath, "", 1)
}
// This is an odd bugfix, will need further testing
r.URL.Path = "/" + r.URL.Path
if strings.HasPrefix(r.URL.Path, "//") {
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/")
}
oauthClientID := ""
tags := make([]string, 0)
session := ctxGetSession(r)
if session != nil {
oauthClientID = session.OauthClientID
alias = session.Alias
tags = session.Tags
}
rawRequest := ""
rawResponse := ""
if RecordDetail(r) {
requestCopy := CopyHttpRequest(r)
// Get the wire format representation
var wireFormatReq bytes.Buffer
requestCopy.Write(&wireFormatReq)
rawRequest = base64.StdEncoding.EncodeToString(wireFormatReq.Bytes())
}
trackEP := false
trackedPath := r.URL.Path
if p := ctxGetTrackedPath(r); p != "" && !ctxGetDoNotTrack(r) {
trackEP = true
trackedPath = p
}
record := AnalyticsRecord{
r.Method,
trackedPath,
r.URL.Path,
r.ContentLength,
r.Header.Get("User-Agent"),
t.Day(),
t.Month(),
t.Year(),
t.Hour(),
errCode,
token,
t,
version,
e.Spec.Name,
e.Spec.APIID,
e.Spec.OrgID,
oauthClientID,
0,
rawRequest,
rawResponse,
GetIPFromRequest(r),
GeoData{},
tags,
alias,
trackEP,
time.Now(),
}
record.GetGeo(GetIPFromRequest(r))
expiresAfter := e.Spec.ExpireAnalyticsAfter
if config.EnforceOrgDataAge {
orgExpireDataTime := e.GetOrgSessionExpiry(e.Spec.OrgID)
if orgExpireDataTime > 0 {
expiresAfter = orgExpireDataTime
}
}
record.SetExpiry(expiresAfter)
if config.AnalyticsConfig.NormaliseUrls.Enabled {
record.NormalisePath()
}
go analytics.RecordHit(record)
}
// Report in health check
ReportHealthCheckValue(e.Spec.Health, BlockedRequestLog, "-1")
//If the config option is not set or is false, add the header
if !config.HideGeneratorHeader {
w.Header().Add("X-Generator", "tyk.io")
}
// Close connections
if config.CloseConnections {
w.Header().Add("Connection", "close")
}
if memProfFile != nil {
pprof.WriteHeapProfile(memProfFile)
}
}