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` выполняется несмотря на `return` в `catch`, и почему `"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.