/
errors.go
158 lines (133 loc) · 4.39 KB
/
errors.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
// Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package xhttp
import (
"context"
"encoding/json"
"errors"
"net/http"
"sync"
"github.com/prometheus/prometheus/promql"
"github.com/m3db/m3/src/dbnode/client"
xerrors "github.com/m3db/m3/src/x/errors"
)
// ErrorRewriteFn is a function for rewriting response error.
type ErrorRewriteFn func(error) error
var (
errorRewriteFn ErrorRewriteFn = func(err error) error { return err }
errorRewriteFnLock sync.RWMutex
)
// Error is an HTTP JSON error that also sets a return status code.
type Error interface {
// Fulfill error interface.
error
// Embedding ContainedError allows for the inner error
// to be retrieved with all existing error helpers.
xerrors.ContainedError
// Code returns the status code to return to end users.
Code() int
}
// NewError creates a new error with an explicit status code
// which will override any wrapped error to return specifically
// the exact error code desired.
func NewError(err error, status int) Error {
return errorWithCode{err: err, status: status}
}
type errorWithCode struct {
err error
status int
}
func (e errorWithCode) Error() string {
return e.err.Error()
}
func (e errorWithCode) InnerError() error {
return e.err
}
func (e errorWithCode) Code() int {
return e.status
}
// ErrorResponse is a generic response for an HTTP error.
type ErrorResponse struct {
Status string `json:"status"`
Error string `json:"error"`
}
type options struct {
response []byte
}
// WriteErrorOption is an option to pass to WriteError.
type WriteErrorOption func(*options)
// WithErrorResponse specifies a response to add the WriteError method.
func WithErrorResponse(b []byte) WriteErrorOption {
return func(o *options) {
o.response = b
}
}
// WriteError will serve an HTTP error.
func WriteError(w http.ResponseWriter, err error, opts ...WriteErrorOption) {
var o options
for _, fn := range opts {
fn(&o)
}
errorRewriteFnLock.RLock()
err = errorRewriteFn(err)
errorRewriteFnLock.RUnlock()
statusCode := getStatusCode(err)
if o.response == nil {
w.Header().Set(HeaderContentType, ContentTypeJSON)
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(ErrorResponse{Status: "error", Error: err.Error()}) //nolint:errcheck
} else {
w.WriteHeader(statusCode)
w.Write(o.response)
}
}
// SetErrorRewriteFn sets error rewrite function.
func SetErrorRewriteFn(f ErrorRewriteFn) ErrorRewriteFn {
errorRewriteFnLock.Lock()
defer errorRewriteFnLock.Unlock()
res := errorRewriteFn
errorRewriteFn = f
return res
}
func getStatusCode(err error) int {
switch v := err.(type) {
case Error:
return v.Code()
case error:
if xerrors.IsInvalidParams(v) {
return http.StatusBadRequest
} else if errors.Is(err, context.Canceled) {
// This status code was coined by Nginx for exactly the same use case.
// https://httpstatuses.com/499
return 499
} else if errors.Is(err, context.DeadlineExceeded) || client.IsTimeoutError(err) {
return http.StatusGatewayTimeout
// Also check for prom errors, which can be either a cancellation or a timeout.
} else if _, ok := err.(promql.ErrQueryCanceled); ok { // nolint:errorlint
return 499
}
}
return http.StatusInternalServerError
}
// IsClientError returns true if this error would result in 4xx status code.
func IsClientError(err error) bool {
code := getStatusCode(err)
return code >= 400 && code < 500
}