-
Notifications
You must be signed in to change notification settings - Fork 0
/
printer.go
75 lines (60 loc) · 1.64 KB
/
printer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package lib
import (
"fmt"
"net"
"net/http"
"github.com/spf13/cobra"
"bunnyshell.com/cli/pkg/formatter"
"bunnyshell.com/sdk"
)
func FormatCommandError(cmd *cobra.Command, err error) error {
FormatCommandData(cmd, map[string]interface{}{
"error": err.Error(),
})
return err
}
func FormatCommandData(cmd *cobra.Command, data interface{}) error {
result, err := formatter.Formatter(data, CLIContext.OutputFormat)
if err != nil {
cmd.PrintErrln(err)
return err
}
cmd.Println(string(result))
return nil
}
func FormatRequestResult(cmd *cobra.Command, data interface{}, r *http.Response, err error) error {
if err != nil {
switch err := err.(type) {
case net.Error:
if err.Timeout() {
return printTimeout(cmd, err)
}
case *sdk.GenericOpenAPIError:
return printOpenAPIError(cmd, err, r)
}
return printGenericError(cmd, err, r)
}
return FormatCommandData(cmd, data)
}
func printGenericError(cmd *cobra.Command, err error, r *http.Response) error {
return FormatCommandData(cmd, map[string]interface{}{
"status": r.StatusCode,
"error": err.Error(),
})
}
func printOpenAPIError(cmd *cobra.Command, err *sdk.GenericOpenAPIError, r *http.Response) error {
switch model := err.Model().(type) {
case sdk.ProblemGeneric:
return FormatCommandData(cmd, &model)
}
data := sdk.NewProblemGeneric()
data.SetTitle(fmt.Sprintf("Response status: %d", r.StatusCode))
data.SetDetail(err.Error())
return FormatCommandData(cmd, data)
}
func printTimeout(cmd *cobra.Command, err error) error {
data := sdk.NewProblemGeneric()
data.SetTitle("Operation timed out")
data.SetDetail(err.Error())
return FormatCommandData(cmd, data)
}