Handle API Errors
Handle API Errors
Task
Translate common HTTP failures into short messages that the prepared error area can display.
Open
Inside the current-weather response check, use the status-specific handling below.
Implementation
if (!response.ok) {
if (response.status === 404) {
throw new Error("City not found. Check the spelling and try again.");
}
if (response.status === 401) {
throw new Error("Invalid API key. Check script.js.");
}
throw new Error("Weather service is unavailable right now.");
}
For the forecast request:
if (!forecastResponse.ok) {
throw new Error("Could not load the forecast.");
}
The browser receives an HTTP status even when the request technically completed. Checking response.ok and then translating important statuses makes the application understandable without exposing raw server details.
Test
Search for a deliberately invalid city. Then, if needed, temporarily use an invalid API key to verify the 401 message and restore the key immediately. Confirm the loader disappears after each failure.
Expected result
Common API failures now produce useful user-facing messages.
Checkpoint
Before moving on, confirm the expected result in the running app and make sure the browser console has no blocking errors.