Handling API Errors
Even the most perfectly coded applications will encounter errors. Network connections drop, API keys expire, and users type in invalid parameters. A robust application must gracefully handle these exceptions instead of crashing or showing a white screen.
Catching Network Failures
2.17.1Before you even worry about API status codes, you must handle raw network failures. If the user is offline or their DNS fails, the fetch() promise will reject entirely. Wrap your API calls in a try/catch block.
try {
const response = await fetch(url);
// Process response...
} catch (error) {
// This triggers if the user has no internet connection
console.error("Network failure:", error);
alert("Please check your internet connection and try again.");
}Parsing SdashAPI Error Messages
2.17.2If the network request succeeds but the SdashAPI backend rejects it (e.g., due to an invalid API key), the response will still be valid JSON. However, instead of a data array, you will receive a message string explaining the error.
{
"status": 401,
"message": "Missing or invalid AccessToken."
}Checking the ok Property
2.17.3In JavaScript, a 404 or 500 status code does not cause the fetch() promise to reject. You must manually check the response.ok boolean before attempting to parse the normal data payload.
const response = await fetch(url);
if (!response.ok) {
// The server returned a 4xx or 5xx code
const errorJson = await response.json();
throw new Error(errorJson.message);
}
// If we reach here, response.ok is true (200 OK)
const data = await response.json();