Refactor API response handling for better error messaging.