Handle docker API errors

This commit is contained in:
Timofey 2021-04-17 16:36:23 +03:00 committed by Umputun
parent 813ed6df3d
commit e7121846da
2 changed files with 26 additions and 1 deletions

View File

@ -324,7 +324,19 @@ func (d *dockerClient) ListContainers() ([]containerInfo, error) {
defer resp.Body.Close()
var response []struct {
if resp.StatusCode != http.StatusOK {
e := struct {
Message string `json:"message"`
}{}
if err := json.NewDecoder(resp.Body).Decode(&e); err != nil {
return nil, fmt.Errorf("failed to parse error from docker daemon: %w", err)
}
return nil, fmt.Errorf("unexpected error from docker daemon: %s", e.Message)
}
response := []struct {
ID string `json:"Id"`
Name string
State string

View File

@ -201,3 +201,16 @@ func TestDockerClient(t *testing.T) {
assert.Empty(t, c[1].IP)
}
func TestDockerClient_error(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, `{"message": "bruh"}`, http.StatusInternalServerError)
}))
defer srv.Close()
addr := fmt.Sprintf("tcp://%s", strings.TrimPrefix(srv.URL, "http://"))
client := NewDockerClient(addr, "bridge")
_, err := client.ListContainers()
require.EqualError(t, err, "unexpected error from docker daemon: bruh")
}