From 66d1e8cc1238e7c5935ef23f3ba3841f1c3c69dd Mon Sep 17 00:00:00 2001 From: Christophe Fergeau Date: Thu, 22 Jun 2023 17:18:24 +0200 Subject: [PATCH] json: Improve error handling The goal is to return an error as soon as a parsing error occurs. The current code would sometimes ignore parsing errors and try to parse as much as it can, which would give a partial VM representation, which is not desirable. Signed-off-by: Christophe Fergeau --- pkg/config/json.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/pkg/config/json.go b/pkg/config/json.go index 1452e3b6..15ba5bc5 100644 --- a/pkg/config/json.go +++ b/pkg/config/json.go @@ -58,10 +58,10 @@ func unmarshalBootloader(rawMsg json.RawMessage) (Bootloader, error) { bootloader = &linux } default: - return nil, fmt.Errorf("unknown 'kind' field: '%s'", kind) + err = fmt.Errorf("unknown 'kind' field: '%s'", kind) } - return bootloader, nil + return bootloader, err } func unmarshalDevices(rawMsg json.RawMessage) ([]VirtioDevice, error) { @@ -71,15 +71,19 @@ func unmarshalDevices(rawMsg json.RawMessage) ([]VirtioDevice, error) { ) err := json.Unmarshal(rawMsg, &rawDevices) + if err != nil { + return nil, err + } for _, msg := range rawDevices { dev, err := unmarshalDevice(*msg) - if err == nil { - devices = append(devices, dev) + if err != nil { + return nil, err } + devices = append(devices, dev) } - return devices, err + return devices, nil } func unmarshalDevice(rawMsg json.RawMessage) (VirtioDevice, error) { @@ -129,7 +133,7 @@ func unmarshalDevice(rawMsg json.RawMessage) (VirtioDevice, error) { err = json.Unmarshal(rawMsg, &newDevice) dev = &newDevice default: - return nil, fmt.Errorf("unknown 'kind' field: '%s'", kind) + err = fmt.Errorf("unknown 'kind' field: '%s'", kind) } if err != nil {