/
error.go
42 lines (35 loc) · 1.34 KB
/
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
package server
import (
"context"
"errors"
"net/http"
"github.com/cortexproject/cortex/pkg/chunk"
"github.com/weaveworks/common/httpgrpc"
"github.com/famarks/loki/pkg/logql"
)
// StatusClientClosedRequest is the status code for when a client request cancellation of an http request
const StatusClientClosedRequest = 499
const (
ErrClientCanceled = "The request was cancelled by the client."
ErrDeadlineExceeded = "Request timed out, decrease the duration of the request or add more label matchers (prefer exact match over regex match) to reduce the amount of data processed."
)
// WriteError write a go error with the correct status code.
func WriteError(err error, w http.ResponseWriter) {
var queryErr chunk.QueryError
switch {
case errors.Is(err, context.Canceled):
http.Error(w, ErrClientCanceled, StatusClientClosedRequest)
case errors.Is(err, context.DeadlineExceeded):
http.Error(w, ErrDeadlineExceeded, http.StatusGatewayTimeout)
case errors.As(err, &queryErr):
http.Error(w, err.Error(), http.StatusBadRequest)
case logql.IsParseError(err) || logql.IsPipelineError(err):
http.Error(w, err.Error(), http.StatusBadRequest)
default:
if grpcErr, ok := httpgrpc.HTTPResponseFromError(err); ok {
http.Error(w, string(grpcErr.Body), int(grpcErr.Code))
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}