-
Notifications
You must be signed in to change notification settings - Fork 66
/
error_source_middleware.go
38 lines (32 loc) · 1.33 KB
/
error_source_middleware.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
package errorsource
import (
"errors"
"net/http"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/backend/httpclient"
)
// Middleware captures error source metric
// Deprecated: If you are using sdk httpclient, this is already included in the default middleware.
// If you are not using the sdk httpclient, you should use httpclient.ErrorSourceMiddleware instead.
func Middleware(plugin string) httpclient.Middleware {
return httpclient.NamedMiddlewareFunc(plugin, RoundTripper)
}
// RoundTripper returns the error source
// Deprecated: If you are using sdk httpclient, this is already included in the default middleware.
// If you are not using the sdk httpclient, you should use httpclient.ErrorSourceRoundTripper instead.
func RoundTripper(_ httpclient.Options, next http.RoundTripper) http.RoundTripper {
return httpclient.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
res, err := next.RoundTrip(req)
if res != nil && res.StatusCode >= 400 {
errorSource := backend.ErrorSourceFromHTTPStatus(res.StatusCode)
if err == nil {
err = errors.New(res.Status)
}
return res, backend.NewErrorWithSource(err, errorSource)
}
if backend.IsDownstreamHTTPError(err) {
return res, backend.NewErrorWithSource(err, backend.ErrorSourceDownstream)
}
return res, err
})
}