Skip to content

Commit

Permalink
[query] Handle context.Canceled and map to 499 http status (#3069)
Browse files Browse the repository at this point in the history
  • Loading branch information
Antanukas authored Jan 26, 2021
1 parent 358d92a commit 0d41634
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 6 deletions.
4 changes: 4 additions & 0 deletions src/x/net/http/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@ func getStatusCode(err error) int {
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) {
return http.StatusGatewayTimeout
}
Expand Down
52 changes: 46 additions & 6 deletions src/x/net/http/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
package xhttp

import (
"context"
"errors"
"fmt"
"net/http/httptest"
Expand All @@ -32,40 +33,79 @@ import (
xerrors "github.com/m3db/m3/src/x/errors"
)

func TestErrorRewrite(t *testing.T) {
func TestErrorStatus(t *testing.T) {
tests := []struct {
name string
err error
expectedStatus int
}{
{
name: "generic error",
err: errors.New("generic error"),
expectedStatus: 500,
},
{
name: "invalid params",
err: xerrors.NewInvalidParamsError(errors.New("bad param")),
expectedStatus: 400,
},
{
name: "deadline exceeded",
err: context.DeadlineExceeded,
expectedStatus: 504,
},
{
name: "canceled",
err: context.Canceled,
expectedStatus: 499,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
WriteError(recorder, tt.err)
assert.Equal(t, tt.expectedStatus, recorder.Code)
})
}
}

func TestErrorRewrite(t *testing.T) {
tests := []struct {
name string
err error
expectedBody string
expectedStatus int
}{
{
name: "error that should not be rewritten",
err: errors.New("random error"),
expectedStatus: 500,
expectedBody: `{"status":"error","error":"random error"}`,
expectedStatus: 500,
},
{
name: "error that should be rewritten",
err: xerrors.NewInvalidParamsError(errors.New("to be rewritten")),
expectedStatus: 500,
expectedBody: `{"status":"error","error":"rewritten error"}`,
expectedStatus: 500,
},
}

SetErrorRewriteFn(func(err error) error {
invalidParamsRewriteFn := func(err error) error {
if xerrors.IsInvalidParams(err) {
return errors.New("rewritten error")
}
return err
})
}

SetErrorRewriteFn(invalidParamsRewriteFn)

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
WriteError(recorder, tt.err)
assert.Equal(t, tt.expectedStatus, recorder.Code)
assert.JSONEq(t, tt.expectedBody, recorder.Body.String())
assert.Equal(t, tt.expectedStatus, recorder.Code)
})
}
}
Expand Down

0 comments on commit 0d41634

Please sign in to comment.