From 2cac37c1fbc7eb15976dea04b7c599819df07cd9 Mon Sep 17 00:00:00 2001 From: Pascal Precht <445106+PascalPrecht@users.noreply.github.com> Date: Thu, 15 Sep 2022 10:10:00 +0200 Subject: [PATCH] fix(images): ensure decode from URL emits error on HTTP error code We should emit an error when the request to an image to be fetched returns and HTTP error code. Otherwise, we'll run into other higher level errors down the line, which are misleading Example: I kept seeing "image content type not supported" errors, although the content type *is* supported. The actual problem was that the decode function operates on non existing image bytes. --- images/decode.go | 4 ++++ images/decode_test.go | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/images/decode.go b/images/decode.go index 140adf16d..dc1315909 100644 --- a/images/decode.go +++ b/images/decode.go @@ -48,6 +48,10 @@ func DecodeFromURL(path string) (image.Image, error) { } }() + if res.StatusCode >= 400 { + return nil, errors.New(http.StatusText(res.StatusCode)) + } + bodyBytes, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err diff --git a/images/decode_test.go b/images/decode_test.go index 5cccf5cd8..7df58ee1e 100644 --- a/images/decode_test.go +++ b/images/decode_test.go @@ -150,6 +150,14 @@ func TestDecodeFromURL(t *testing.T) { } } +func TestDecodeFromURL_WithErrors(t *testing.T) { + s := httptest.NewServer(http.FileServer(http.Dir(path))) + defer s.Close() + + _, err := DecodeFromURL("https://doesnt-exist.com") + require.Error(t, err) +} + func TestGetType(t *testing.T) { cs := []struct { Buf []byte