JavaScript
Fetch с таймаутом и обработкой ошибок
Обёртка над fetch: AbortController для таймаута, проверка response.ok, разбор JSON.
Код
async function fetchJSON(url, { timeout = 10000, ...options } = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
...options,
signal: controller.signal,
headers: { 'Content-Type': 'application/json', ...options.headers },
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
if (error.name === 'AbortError') {
throw new Error(`Превышено время ожидания (${timeout} мс)`);
}
throw error;
} finally {
clearTimeout(timer);
}
}
fetchJSON('/api/users/')
.then((users) => console.log(users))
.catch((error) => console.error('Не удалось загрузить:', error.message));