Skip to content

Commit d3b85f9

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

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

cmd/compose/compose.go

Lines changed: 35 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"
@@ -98,6 +99,9 @@ func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
9899
Status: err.Error(),
99100
}
100101
}
102+
if ui.Mode == ui.ModeJSON {
103+
err = makeJSONError(err)
104+
}
101105
return err
102106
}
103107
}
@@ -152,6 +156,37 @@ func (o *ProjectOptions) WithServices(dockerCli command.Cli, fn ProjectServicesF
152156
})
153157
}
154158

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

0 commit comments

Comments
 (0)