-
Notifications
You must be signed in to change notification settings - Fork 4
/
printer.go
84 lines (64 loc) · 1.78 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
76
77
78
79
80
81
82
83
84
package lib
import (
"errors"
"fmt"
"net"
"net/http"
"bunnyshell.com/cli/pkg/config"
"bunnyshell.com/cli/pkg/formatter"
"bunnyshell.com/sdk"
"github.com/spf13/cobra"
)
var ErrGeneric = errors.New("oops! Something went wrong")
func FormatCommandError(cmd *cobra.Command, err error) error {
_ = FormatCommandData(cmd, err)
return ErrGeneric
}
func FormatCommandData(cmd *cobra.Command, data interface{}) error {
result, err := formatter.Formatter(data, config.GetSettings().OutputFormat)
if err != nil {
cmd.PrintErrln(err)
return err
}
cmd.Println(string(result))
return nil
}
func FormatRequestResult(cmd *cobra.Command, data interface{}, resp *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, resp)
}
return printGenericError(cmd, err, resp)
}
return FormatCommandData(cmd, data)
}
func printGenericError(cmd *cobra.Command, err error, resp *http.Response) error {
result := map[string]interface{}{
"error": err.Error(),
}
if resp != nil {
result["status"] = resp.StatusCode
}
return FormatCommandData(cmd, result)
}
func printOpenAPIError(cmd *cobra.Command, err *sdk.GenericOpenAPIError, resp *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", resp.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)
}