Skip to content

Commit

Permalink
ignore unknown monitor type in FindMonitors
Browse files Browse the repository at this point in the history
  • Loading branch information
mechairoi committed Mar 27, 2023
1 parent 49fe562 commit af37d69
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
17 changes: 16 additions & 1 deletion monitors.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,12 @@ func (c *Client) FindMonitors() ([]Monitor, error) {
for _, rawmes := range data.Monitors {
m, err := decodeMonitor(rawmes)
if err != nil {
return nil, err
switch err.(type) {
case *unknownMonitorTypeError:
break
default:
return nil, err
}
}
ms = append(ms, m)
}
Expand Down Expand Up @@ -397,6 +402,14 @@ func (c *Client) DeleteMonitor(monitorID string) (Monitor, error) {
return decodeMonitorReader(resp.Body)
}

type unknownMonitorTypeError struct {
Type string
}

func (e *unknownMonitorTypeError) Error() string {
return fmt.Sprintf("unknown monitor type: %s", e.Type)
}

// decodeMonitor decodes json.RawMessage and returns monitor.
func decodeMonitor(mes json.RawMessage) (Monitor, error) {
var typeData struct {
Expand All @@ -419,6 +432,8 @@ func decodeMonitor(mes json.RawMessage) (Monitor, error) {
m = &MonitorExpression{}
case monitorTypeAnomalyDetection:
m = &MonitorAnomalyDetection{}
default:
return nil, &unknownMonitorTypeError{Type: typeData.Type}
}
if err := json.Unmarshal(mes, m); err != nil {
return nil, err
Expand Down
21 changes: 21 additions & 0 deletions monitors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,27 @@ func TestDecodeEncodeMonitor(t *testing.T) {
}
}

func TestDecodeUnknownMonitor(t *testing.T) {
json := `{
"id" : "2cSZzK3XfmE",
"type": "unknown",
"unknownField": "unknownValue"
}`
gotMonitor, err := decodeMonitorReader(strings.NewReader(json))
if gotMonitor != nil {
t.Errorf("gotMonitor should be nil but: %v", gotMonitor)
}
if err == nil {
t.Errorf("err should be unknownMonitorTypeError but: %v", err)
} else {
switch err.(type) {
case *unknownMonitorTypeError:
default:
t.Errorf("err should be unknownMonitorTypeError but: %v", err)
}
}
}

func equalJSON(x, y string) bool {
var xval, yval interface{}
json.Unmarshal([]byte(x), &xval) //nolint
Expand Down

0 comments on commit af37d69

Please sign in to comment.