forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_error.go
107 lines (89 loc) · 2.56 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
package main
import (
"fmt"
"github.com/gorilla/context"
"net/http"
"runtime/pprof"
"strings"
"time"
)
// 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, err string, errCode int) {
if config.StoreAnalytics(r) {
t := time.Now()
// Track the key ID if it exists
authHeaderValue := context.Get(r, AuthHeaderValue)
keyName := ""
if authHeaderValue != nil {
keyName = authHeaderValue.(string)
}
version := e.Spec.getVersionFromRequest(r)
if version == "" {
version = "Non Versioned"
}
if e.TykMiddleware.Spec.APIDefinition.Proxy.StripListenPath {
r.URL.Path = strings.Replace(r.URL.Path, e.TykMiddleware.Spec.Proxy.ListenPath, "", 1)
}
// This is an odd bugfix, will need further testing
r.URL.Path = "/" + r.URL.Path
OauthClientID := ""
thisSessionState := context.Get(r, SessionData)
if thisSessionState != nil {
OauthClientID = thisSessionState.(SessionState).OauthClientID
}
thisRecord := AnalyticsRecord{
r.Method,
r.URL.Path,
r.ContentLength,
r.Header.Get("User-Agent"),
t.Day(),
t.Month(),
t.Year(),
t.Hour(),
errCode,
keyName,
t,
version,
e.Spec.APIDefinition.Name,
e.Spec.APIDefinition.APIID,
e.Spec.APIDefinition.OrgID,
OauthClientID,
0,
time.Now(),
}
expiresAfter := e.Spec.ExpireAnalyticsAfter
if config.EnforceOrgDataAge {
thisOrg := e.Spec.OrgID
orgSessionState, found := e.GetOrgSession(thisOrg)
if found {
if orgSessionState.DataExpires > 0 {
expiresAfter = orgSessionState.DataExpires
}
}
}
thisRecord.SetExpiry(expiresAfter)
go analytics.RecordHit(thisRecord)
}
// Report in health check
ReportHealthCheckValue(e.Spec.Health, BlockedRequestLog, "1")
w.Header().Add("Content-Type", "application/json")
w.Header().Add("X-Generator", "tyk.io")
log.Debug("Returning error header")
w.WriteHeader(errCode)
thisError := APIError{fmt.Sprintf("%s", err)}
templates.ExecuteTemplate(w, "error.json", &thisError)
if doMemoryProfile {
pprof.WriteHeapProfile(profileFile)
}
// Clean up
context.Clear(r)
}