Sobes.tech
Middle+

Code review: issues in the function getExternalOrderIdFromCRM (HTTP client)

sobes.tech AI

Answer from AI

When reviewing the getExternalOrderIdFromCRM function that uses an HTTP client, consider the following points:

  • Error handling: ensure that all possible errors (network, timeouts, invalid responses) are properly handled and do not cause panics.
  • Timeouts: HTTP requests should have a timeout limit to prevent hanging.
  • Retry logic: if requests to CRM can temporarily fail, implement retry logic with exponential backoff.
  • Response parsing: verify that the response is correctly deserialized and consider possible format changes.
  • Logging: it is useful to log requests and responses for debugging.

An improved code example with timeout and error handling:

func getExternalOrderIdFromCRM(client *http.Client, url string) (string, error) {
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return "", err
    }

    ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second)
    defer cancel()
    req = req.WithContext(ctx)

    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
    }

    var result struct {
        OrderID string `json:"order_id"`
    }
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        return "", err
    }

    return result.OrderID, nil
}

This approach makes the function more reliable and easier to maintain.

Code review: issues in the function… - sobes.tech