Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

ProductBarcode: backend: fix error handling with http requests

Crumb Owl8dedfcca43ef
diff --git a/backend/app/api/handlers/v1/v1_ctrl_product_search.go b/backend/app/api/handlers/v1/v1_ctrl_product_search.go
index db7caca4..b4de9f07 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_product_search.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_product_search.go
@@ -124,7 +124,10 @@ func (ctrl *V1Controller) HandleProductSearchFromBarcode(conf config.BarcodeAPIC
if err != nil {
return nil, err
}
- defer resp.Body.Close()
+
+ defer func() {
+ err = errors.Join(err, resp.Body.Close())
+ }()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API returned status code: %d", resp.StatusCode)
@@ -193,6 +196,12 @@ func (ctrl *V1Controller) HandleProductSearchFromBarcode(conf config.BarcodeAPIC
return nil, err
}
+ // defer the call to Body.Close(). We also check the error code, and merge
+ // it with the other error in this code to avoid error overiding.
+ defer func() {
+ err = errors.Join(err, resp.Body.Close())
+ }()
+
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("barcodespider API returned status code: %d", resp.StatusCode)
}
@@ -203,8 +212,6 @@ func (ctrl *V1Controller) HandleProductSearchFromBarcode(conf config.BarcodeAPIC
return nil, err
}
- resp.Body.Close()
-
// Convert the body to type string
sb := string(body)
log.Info().Msg("Response: " + sb)
@@ -260,15 +267,17 @@ func (ctrl *V1Controller) HandleProductSearchFromBarcode(conf config.BarcodeAPIC
log.Warn().Msg("Cannot fetch image for URL: " + p.ImageURL + ": " + err.Error())
}
+ defer func() {
+ err = errors.Join(err, res.Body.Close())
+ }()
+
// Validate response
if res.StatusCode != http.StatusOK {
- res.Body.Close()
continue
}
// Read data of image
bytes, err := io.ReadAll(res.Body)
- res.Body.Close()
if err != nil {
log.Warn().Msg(err.Error())
continue