Skip to content

Commit 150e636

Browse files
committed
Format errors as JSON when in JSON progress mode.
Signed-off-by: Felix Fontein <[email protected]>
1 parent b588c7d commit 150e636

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

cmd/compose/compose.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package compose
1818

1919
import (
2020
"context"
21+
"encoding/json"
2122
"errors"
2223
"fmt"
2324
"os"
@@ -99,6 +100,9 @@ func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
99100
Status: err.Error(),
100101
}
101102
}
103+
if ui.Mode == ui.ModeJSON {
104+
err = makeJSONError(err)
105+
}
102106
return err
103107
}
104108
}
@@ -154,6 +158,38 @@ func (o *ProjectOptions) WithServices(dockerCli command.Cli, fn ProjectServicesF
154158
})
155159
}
156160

161+
type jsonErrorData struct {
162+
Error bool `json:"error,omitempty"`
163+
Message string `json:"message,omitempty"`
164+
}
165+
166+
func errorAsJSON(message string) string {
167+
errorMessage := &jsonErrorData{
168+
Error: true,
169+
Message: message,
170+
}
171+
marshal, err := json.Marshal(errorMessage)
172+
if err == nil {
173+
return string(marshal)
174+
} else {
175+
return message
176+
}
177+
}
178+
179+
func makeJSONError(err error) error {
180+
if err == nil {
181+
return nil
182+
}
183+
var statusErr dockercli.StatusError
184+
if errors.As(err, &statusErr) {
185+
return dockercli.StatusError{
186+
StatusCode: statusErr.StatusCode,
187+
Status: errorAsJSON(statusErr.Status),
188+
}
189+
}
190+
return fmt.Errorf("%s", errorAsJSON(err.Error()))
191+
}
192+
157193
func (o *ProjectOptions) addProjectFlags(f *pflag.FlagSet) {
158194
f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
159195
f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")

0 commit comments

Comments
 (0)