Skip to content

Commit 44f37cb

Browse files
committed
Issue #951 Send errors back encoded as JSON
Add a new commandError struct to report command errors and json encoding errors
1 parent 6694413 commit 44f37cb

3 files changed

Lines changed: 22 additions & 5 deletions

File tree

pkg/crc/api/api.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,13 @@ func (api CrcApiServer) handleClusterOperations() {
5050

5151
func (api CrcApiServer) handleRequest(req commandRequest, conn net.Conn) {
5252
defer conn.Close()
53+
var result string
5354
if handler, ok := api.handlers[req.Command]; ok {
54-
result := handler(req.Args)
55-
writeStringToSocket(conn, result)
55+
result = handler(req.Args)
5656
} else {
57-
writeStringToSocket(conn, fmt.Sprintf("Unknown command supplied: %s", req.Command))
57+
result = encodeErrorToJson(fmt.Sprintf("Unknown command supplied: %s", req.Command))
5858
}
59+
writeStringToSocket(conn, result)
5960
}
6061

6162
func (api CrcApiServer) handleConnections(conn net.Conn) {
@@ -84,7 +85,8 @@ func (api CrcApiServer) handleConnections(conn net.Conn) {
8485
if !addRequestToChannel(r, api.clusterOpsRequestsChan) {
8586
defer conn.Close()
8687
logging.Error("Channel capacity reached, unable to add new request")
87-
writeStringToSocket(conn, "Channel capacity reached, unable to add new request")
88+
errMsg := encodeErrorToJson("Sockets channel capacity reached, unable to add new request")
89+
writeStringToSocket(conn, errMsg)
8890
return
8991
}
9092
} else {

pkg/crc/api/handlers.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,18 @@ func encodeStructToJson(v interface{}) string {
8080
s, err := json.Marshal(v)
8181
if err != nil {
8282
logging.Error(err.Error())
83-
return "Failed"
83+
err := commandError{
84+
Err: "Failed while encoding JSON to string",
85+
}
86+
s, _ := json.Marshal(err)
87+
return string(s)
8488
}
8589
return string(s)
8690
}
91+
92+
func encodeErrorToJson(errMsg string) string {
93+
err := commandError{
94+
Err: errMsg,
95+
}
96+
return encodeStructToJson(err)
97+
}

pkg/crc/api/types.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ import (
77
type ArgsType map[string]string
88
type handlerFunc func(ArgsType) string
99

10+
type commandError struct {
11+
Err string
12+
}
13+
1014
type CrcApiServer struct {
1115
listener net.Listener
1216
clusterOpsRequestsChan chan clusterOpsRequest

0 commit comments

Comments
 (0)