Sobes.tech
Intern

How to improve an application so that it does not crash when an external API error occurs?

sobes.tech AI

Answer from AI

To prevent the application from crashing due to external API errors, error handling and resilience mechanisms should be implemented:

  • Use try/catch blocks (or similar constructs) to catch exceptions when calling the API.
  • Add timeouts and retries with exponential backoff.
  • Use fallback logic: for example, return cached data or default values.
  • Log errors for subsequent analysis.
  • If necessary, apply a circuit breaker to temporarily disable calls to a problematic API during frequent errors.

Example in Go with error handling and retry:

func callExternalAPI() (string, error) {
    var result string
    var err error
    for i := 0; i < 3; i++ { // three attempts
        result, err = doRequest()
        if err == nil {
            return result, nil
        }
        time.Sleep(time.Duration(i*i) * time.Second) // exponential delay
    }
    return "", fmt.Errorf("failed after retries: %w", err)
}