JavaScript · Синтаксис · Просунутий рівень
Обробка помилок
Власні помилки, try/catch/finally, async помилки та захисні патерни
Короткий вступ до теми та пояснення перед вправами (вправи нижче):
Async помилки, Promise.allSettled та safeParseJSON
#Патерн Result, довідник обробки помилок та типові помилки
#Вправи:
Реалізуйте власний клас ValidationError
#Створіть клас `ValidationError` що розширює `Error`. Конструктор приймає `message` та `field`. Встановіть `this.name = "ValidationError"`. Перевірте що `instanceof ValidationError` та `instanceof Error` обидва повертають `true`.
class ValidationError extends Error {
// add: name='ValidationError', field property
}
// Test:
try {
throw new ValidationError('email is required', 'email');
} catch (err) {
console.log(err.name); // 'ValidationError'
console.log(err.message); // 'email is required'
console.log(err.field); // 'email'
console.log(err instanceof ValidationError); // true
console.log(err instanceof Error); // true
}
Рішення
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
try {
throw new ValidationError('email is required', 'email');
} catch (err) {
console.log(err.name); // 'ValidationError'
console.log(err.message); // 'email is required'
console.log(err.field); // 'email'
console.log(err instanceof ValidationError); // true
console.log(err instanceof Error); // true
}
Передбачте порядок виконання try/catch/finally
#Який точний вивід цього коду? Поясніть чому `finally` виконується хоча `catch` має `return`, та чому `"after throw"` ніколи не логується.
function test() {
try {
console.log('try');
throw new Error('oops');
console.log('after throw');
} catch (e) {
console.log('catch:', e.message);
return 'from catch';
} finally {
console.log('finally');
}
}
const result = test();
console.log('result:', result);
Рішення
// Output order:
// try
// catch: oops
// finally ← runs before the return from catch lands
// result: from catch
// 'after throw' is never logged because execution jumps to catch
// finally always runs even when catch has a return statement
Обробіть async помилки з try/catch
#Реалізуйте `fetchData(url)` як `async` функцію. Використайте `fetch` для запиту. Якщо `res.ok` хибний — кидайте `Error` з HTTP-статусом. Ловіть будь-яку помилку, логуйте `"fetchData failed: <message>"` та повертайте `null`.
async function fetchData(url) {
// fetch url, throw if !res.ok (include HTTP status in message)
// on error: log the message and return null
}
Рішення
async function fetchData(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP error: ${res.status}`);
return await res.json();
} catch (err) {
console.error('fetchData failed:', err.message);
return null;
}
}
Отримайте кілька URL з Promise.allSettled
#Реалізуйте `fetchAll(urls)` що паралельно запитує всі URL та повертає `{ succeeded: [...responses], failed: [...errorMessages] }`. Деякі запити можуть не вдатися — не дозволяйте одній невдачі скасувати інші.
async function fetchAll(urls) {
// fetch all urls concurrently
// return { succeeded: [...responses], failed: [...errorMessages] }
}
Рішення
async function fetchAll(urls) {
const results = await Promise.allSettled(urls.map(u => fetch(u)));
const succeeded = [];
const failed = [];
for (const r of results) {
if (r.status === 'fulfilled') succeeded.push(r.value);
else failed.push(r.reason.message);
}
return { succeeded, failed };
}
Вибірково обробіть та перекиньте помилки
#Завершіть `handleRequest()` щоб вибірково обробляти `NetworkError` (логувати `"retry later"`) та `AuthError` (логувати `"please log in"`). Будь-який інший тип помилки має бути перекинутий далі.
class NetworkError extends Error {
constructor(msg) { super(msg); this.name = 'NetworkError'; }
}
class AuthError extends Error {
constructor(msg) { super(msg); this.name = 'AuthError'; }
}
function handleRequest() {
try {
riskyOperation(); // may throw NetworkError, AuthError, or Error
} catch (err) {
// handle NetworkError: log 'retry later'
// handle AuthError: log 'please log in'
// anything else: re-throw
}
}
Рішення
class NetworkError extends Error {
constructor(msg) { super(msg); this.name = 'NetworkError'; }
}
class AuthError extends Error {
constructor(msg) { super(msg); this.name = 'AuthError'; }
}
function handleRequest() {
try {
riskyOperation();
} catch (err) {
if (err instanceof NetworkError) {
console.log('retry later');
} else if (err instanceof AuthError) {
console.log('please log in');
} else {
throw err; // unexpected — propagate
}
}
}
Реалізуйте safeParseJSON із запасним варіантом
#Реалізуйте `safeParseJSON(str, fallback = null)` що намагається розібрати `str` як JSON. Якщо розбір не вдається — поверніть `fallback` замість кидання помилки. Функція не повинна кидати.
function safeParseJSON(str, fallback = null) {
// parse JSON safely, return fallback on invalid input
}
Рішення
function safeParseJSON(str, fallback = null) {
try {
return JSON.parse(str);
} catch {
return fallback;
}
}
safeParseJSON('{"name":"Alice"}'); // {name: 'Alice'}
safeParseJSON('invalid json'); // null
safeParseJSON('bad', []); // []
safeParseJSON('bad', { default: true }); // { default: true }
Зберіть кілька помилок валідації перед кидком
#Реалізуйте `AggregateError` (розширює `Error`, зберігає масив `.errors`) та `validateUser(data)`. Перевірте: `name` непорожній рядок, `age` число ≥ 0, `email` містить `"@"`. Зберіть ВСІ помилки та кидайте один `AggregateError` якщо є будь-які.
class AggregateError extends Error {
constructor(errors, message) {
// errors is an array of Error objects
// store them on this.errors
}
}
function validateUser(data) {
const errors = [];
// validate: data.name must be non-empty string
// validate: data.age must be a number >= 0
// validate: data.email must contain '@'
// if any errors, throw AggregateError with message 'Validation failed'
}
Рішення
class AggregateError extends Error {
constructor(errors, message) {
super(message);
this.name = 'AggregateError';
this.errors = errors;
}
}
function validateUser(data) {
const errors = [];
if (!data.name || typeof data.name !== 'string')
errors.push(new Error('name must be a non-empty string'));
if (typeof data.age !== 'number' || data.age < 0)
errors.push(new Error('age must be a non-negative number'));
if (!data.email || !data.email.includes('@'))
errors.push(new Error('email must contain @'));
if (errors.length) throw new AggregateError(errors, 'Validation failed');
}
try {
validateUser({ name: '', age: -1, email: 'bad' });
} catch (err) {
console.log(err.message); // 'Validation failed'
err.errors.forEach(e => console.log(' -', e.message));
}
Реалізуйте патерн Result для обробки помилок
#Реалізуйте `divide(a, b)` та `safeSqrt(n)` використовуючи патерн Result: повертайте `{ ok: true, value }` при успіху та `{ ok: false, error }` при невдачі. Жодна функція не повинна кидати. Ділення на нуль та квадратний корінь з від'ємного числа — випадки помилок.
function divide(a, b) {
// return { ok: true, value } or { ok: false, error }
// do NOT throw
}
function safeSqrt(n) {
// return { ok: true, value } or { ok: false, error }
// n < 0 is an error
}
Рішення
function divide(a, b) {
if (b === 0) return { ok: false, error: 'division by zero' };
return { ok: true, value: a / b };
}
function safeSqrt(n) {
if (n < 0) return { ok: false, error: 'cannot take sqrt of negative number' };
return { ok: true, value: Math.sqrt(n) };
}
// Usage:
const r1 = divide(10, 2);
if (r1.ok) console.log(r1.value); // 5
const r2 = divide(10, 0);
if (!r2.ok) console.log(r2.error); // 'division by zero'
const r3 = safeSqrt(-4);
if (!r3.ok) console.log(r3.error); // 'cannot take sqrt of negative number'
Зчепіть помилки з параметром cause
#Реалізуйте `loadConfig(path)` що читає файл через `readFile(path)` та розбирає через `JSON.parse`. Ловіть будь-яку помилку та огортайте її: `throw new Error("Failed to load config", { cause: err })`. Це зберігає оригінальну помилку в `.cause`.
// Error cause chaining: new Error('msg', { cause: originalErr })
async function loadConfig(path) {
// read file (simulate: may throw 'file not found' Error)
// parse JSON (may throw SyntaxError)
// wrap any error with cause and message 'Failed to load config'
}
// Simulate helpers:
async function readFile(path) {
if (path === 'missing.json') throw new Error('file not found');
return '{"valid": true}';
}
Рішення
async function loadConfig(path) {
try {
const text = await readFile(path);
return JSON.parse(text);
} catch (err) {
throw new Error('Failed to load config', { cause: err });
}
}
async function readFile(path) {
if (path === 'missing.json') throw new Error('file not found');
return '{"valid": true}';
}
// Usage:
try {
await loadConfig('missing.json');
} catch (err) {
console.log(err.message); // 'Failed to load config'
console.log(err.cause.message); // 'file not found'
}
Налаштуйте глобальні обробники необробленого відхилення
#Поясніть що таке необроблене відхилення Promise та коли воно виникає. Напишіть реєстрацію глобального обробника для браузера (`window`) та Node.js (`process`). Обробник має логувати `"Unhandled rejection: <reason>"`. Продемонструйте створенням відхиленого Promise без `.catch()`.
// In a browser or Node.js environment:
// Set up a global handler for unhandled Promise rejections
// that logs: 'Unhandled rejection: <reason>'
// In browser:
// window.addEventListener('unhandledrejection', handler)
// In Node.js:
// process.on('unhandledRejection', handler)
// Demonstrate by creating a rejected promise with no .catch()
Рішення
// Browser:
window.addEventListener('unhandledrejection', (event) => {
console.log('Unhandled rejection:', event.reason);
event.preventDefault(); // prevents browser console error
});
// Node.js:
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled rejection:', reason);
});
// Trigger it:
Promise.reject(new Error('forgot to catch me'));
// → 'Unhandled rejection: Error: forgot to catch me'
// Always prefer .catch() or try/catch over relying on this handler —
// this is a last resort to prevent silent failures.