Introduction
Graceful degradation helps your API keep working even if some parts fail. It avoids total crashes and gives users useful responses.
Jump into concepts and practice - no test required
Graceful degradation helps your API keep working even if some parts fail. It avoids total crashes and gives users useful responses.
try { // call external service or risky code return full response; } catch (error) { // fallback response or partial data return degraded response; }
try { const data = await fetchExternalAPI(); return { status: 200, data }; } catch { return { status: 200, data: { message: 'Partial data available' } }; }
try { const user = await getUserFromDB(); const orders = await getOrdersFromDB(); return { user, orders }; } catch { return { user: null, orders: [] }; }
This simple REST API tries to get data from a service. If the service fails, it returns partial data instead of an error. This keeps the API working smoothly.
import express from 'express'; const app = express(); // Simulate external service call async function fetchExternalService() { if (Math.random() < 0.5) { throw new Error('Service down'); } return { info: 'Full data from service' }; } app.get('/data', async (req, res) => { try { const data = await fetchExternalService(); res.status(200).json({ success: true, data }); } catch (error) { // Graceful degradation: return partial data res.status(200).json({ success: true, data: { info: 'Partial data due to service issue' } }); } }); app.listen(3000, () => console.log('API running on http://localhost:3000'));
Always return a success status if you provide useful fallback data.
Log errors internally to fix issues later, but don't expose them to users.
Test your graceful degradation by simulating failures.
Graceful degradation keeps your API working even when parts fail.
It returns simpler or partial data instead of errors.
This improves user experience and reliability.
graceful degradation in REST APIs?function getUserData() {
try {
return fetchUserFromDB();
} catch (error) {
return { name: "Guest", id: 0 };
}
}getUserData() return if the database fetch fails?fetchUserFromDB() works, it returns user data.function getData() {
try {
return fetchData();
} catch (error) {
fallbackData;
}
}fallbackData; but does not return it.return, the function returns undefined on error, breaking graceful degradation.