cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/promapi/errors.go
58lines · modecode
| 1 | package promapi |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net" |
| 9 | "syscall" |
| 10 | |
| 11 | v1 "github.com/prometheus/client_golang/api/prometheus/v1" |
| 12 | ) |
| 13 | |
| 14 | func IsUnavailableError(err error) bool { |
| 15 | var apiErr *v1.Error |
| 16 | if ok := errors.As(err, &apiErr); ok { |
| 17 | return apiErr.Type == v1.ErrServer |
| 18 | } |
| 19 | |
| 20 | return true |
| 21 | } |
| 22 | |
| 23 | type APIError struct { |
| 24 | Status string `json:"status"` |
| 25 | ErrorType v1.ErrorType `json:"errorType"` |
| 26 | Error string `json:"error"` |
| 27 | } |
| 28 | |
| 29 | func decodeError(err error) string { |
| 30 | if errors.Is(err, context.Canceled) { |
| 31 | return context.Canceled.Error() |
| 32 | } |
| 33 | |
| 34 | if errors.Is(err, syscall.ECONNREFUSED) { |
| 35 | return "connection refused" |
| 36 | } |
| 37 | |
| 38 | var neterr net.Error |
| 39 | if ok := errors.As(err, &neterr); ok && neterr.Timeout() { |
| 40 | return "connection timeout" |
| 41 | } |
| 42 | |
| 43 | var apiErr *v1.Error |
| 44 | if ok := errors.As(err, &apiErr); ok { |
| 45 | // {"status":"error","errorType":"timeout","error":"query timed out in expression evaluation"} |
| 46 | // Comes with 503 and ends up being reported as server_error but Detail contains raw JSON |
| 47 | // which we can parse and fix the error type |
| 48 | var v1e APIError |
| 49 | if err2 := json.Unmarshal([]byte(apiErr.Detail), &v1e); err2 == nil && v1e.ErrorType == v1.ErrTimeout { |
| 50 | apiErr.Type = v1.ErrTimeout |
| 51 | apiErr.Msg = v1e.Error |
| 52 | } |
| 53 | |
| 54 | return fmt.Sprintf("%s: %s", apiErr.Type, apiErr.Msg) |
| 55 | } |
| 56 | |
| 57 | return err.Error() |
| 58 | } |
| 59 | |