From 153f859b7499d23fc0300e97adf21110e349fcd2 Mon Sep 17 00:00:00 2001 From: Marco Pracucci Date: Mon, 22 Jun 2020 16:29:35 +0200 Subject: [PATCH] Fixed returned API status code on error (#7435) * Fixed returned API status code on error Signed-off-by: Marco Pracucci * Fixed linter Signed-off-by: Marco Pracucci * Simplified code Signed-off-by: Marco Pracucci --- web/api/v1/api.go | 2 +- web/api/v1/api_test.go | 40 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/web/api/v1/api.go b/web/api/v1/api.go index ac40c398e..df6d2e658 100644 --- a/web/api/v1/api.go +++ b/web/api/v1/api.go @@ -469,7 +469,7 @@ func returnAPIError(err error) *apiError { return nil } - switch err.(type) { + switch errors.Cause(err).(type) { case promql.ErrQueryCanceled: return &apiError{errorCanceled, err} case promql.ErrQueryTimeout: diff --git a/web/api/v1/api_test.go b/web/api/v1/api_test.go index a70a10762..54b8b633c 100644 --- a/web/api/v1/api_test.go +++ b/web/api/v1/api_test.go @@ -1193,7 +1193,7 @@ func testEndpoints(t *testing.T, api *API, tr *testTargetRetriever, testLabelAPI }, }, response: map[string][]metadata{ - "go_threads": []metadata{ + "go_threads": { {textparse.MetricTypeGauge, "Number of OS threads created", ""}, {textparse.MetricTypeGauge, "Number of OS threads that were created.", ""}, }, @@ -1279,7 +1279,7 @@ func testEndpoints(t *testing.T, api *API, tr *testTargetRetriever, testLabelAPI }, }, response: map[string][]metadata{ - "go_threads": []metadata{ + "go_threads": { {textparse.MetricTypeGauge, "Number of OS threads created", ""}, {textparse.MetricTypeGauge, "Number of OS threads that were created.", ""}, }, @@ -2719,6 +2719,42 @@ func TestTSDBStatus(t *testing.T) { } } +func TestReturnAPIError(t *testing.T) { + cases := []struct { + err error + expected errorType + }{ + { + err: promql.ErrStorage{Err: errors.New("storage error")}, + expected: errorInternal, + }, { + err: errors.Wrap(promql.ErrStorage{Err: errors.New("storage error")}, "wrapped"), + expected: errorInternal, + }, { + err: promql.ErrQueryTimeout("timeout error"), + expected: errorTimeout, + }, { + err: errors.Wrap(promql.ErrQueryTimeout("timeout error"), "wrapped"), + expected: errorTimeout, + }, { + err: promql.ErrQueryCanceled("canceled error"), + expected: errorCanceled, + }, { + err: errors.Wrap(promql.ErrQueryCanceled("canceled error"), "wrapped"), + expected: errorCanceled, + }, { + err: errors.New("exec error"), + expected: errorExec, + }, + } + + for _, c := range cases { + actual := returnAPIError(c.err) + testutil.NotOk(t, actual) + testutil.Equals(t, c.expected, actual.typ) + } +} + // This is a global to avoid the benchmark being optimized away. var testResponseWriter = httptest.ResponseRecorder{}