From 72597da50ce903895087828b5fc4b918636366f4 Mon Sep 17 00:00:00 2001 From: jonjohnsonjr Date: Wed, 8 Jul 2020 16:01:51 -0700 Subject: [PATCH] transport: preserve unexpected json errors (#739) --- pkg/v1/remote/transport/error.go | 10 +++++++--- pkg/v1/remote/transport/error_test.go | 5 +++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/pkg/v1/remote/transport/error.go b/pkg/v1/remote/transport/error.go index a215e794f..0f0e92afb 100644 --- a/pkg/v1/remote/transport/error.go +++ b/pkg/v1/remote/transport/error.go @@ -166,10 +166,14 @@ func CheckError(resp *http.Response, codes ...int) error { // https://github.com/docker/distribution/blob/master/docs/spec/api.md#errors structuredError := &Error{} - if err := json.Unmarshal(b, structuredError); err != nil { - structuredError.rawBody = string(b) - } + + // This can fail if e.g. the response body is not valid JSON. That's fine, + // we'll construct an appropriate error string from the body and status code. + _ = json.Unmarshal(b, structuredError) + + structuredError.rawBody = string(b) structuredError.StatusCode = resp.StatusCode structuredError.request = resp.Request + return structuredError } diff --git a/pkg/v1/remote/transport/error_test.go b/pkg/v1/remote/transport/error_test.go index 85bd12792..ededc5096 100644 --- a/pkg/v1/remote/transport/error_test.go +++ b/pkg/v1/remote/transport/error_test.go @@ -89,6 +89,11 @@ func TestCheckErrorNotError(t *testing.T) { code: http.StatusBadRequest, body: "", msg: "unsupported status code 400", + }, { + code: http.StatusUnauthorized, + // Valid JSON, but not a structured error -- we should still print the body. + body: `{"details":"incorrect username or password"}`, + msg: `unsupported status code 401; body: {"details":"incorrect username or password"}`, }, { code: http.StatusUnauthorized, body: "Not JSON",