Async error strategies
Learn different error-catching strategies for promises and async functions.
try/catch in async functions
Inside an async function, when a promise awaited with await rejects, the error is caught by the try block. You use the same try/catch structure as in synchronous code.
async function loadProfile(id) {
try {
const profile = await fetchProfile(id);
return profile;
} catch (err) {
console.error('Loading failed', err);
return null;
}
} .catch chain or try/await?
In a promise chain .catch() catches the error. In an async function try/await/catch reads more naturally. Both give the same result; you pick based on the flow.
// chain style
fetchProfile(id).catch(err => logError(err));
// async style
async function load() {
try { await fetchProfile(id); }
catch (err) { logError(err); }
} Exercise Async settings loader
Write an async function loadSettings. In a try block assign the result of await fetchSettings() to const settings and return settings. In a catch (err) block call console.error(err) and return null.
Show example solution
async function loadSettings() {
try {
const settings = await fetchSettings();
return settings;
} catch (err) {
console.error(err);
return null;
}
}
Test yourself
-
How is a rejected promise caught in an async function?
- Only with .then()
- Only with window.onerror
- Only with a finally block
- By wrapping await in try and using catch
Show answer
By wrapping await in try and using catch — Correct! You wrap await in try and catch it.
-
Call with await
async function loadItem() { try { const item = ____ fetchItem(); return item; } catch (err) { logError(err); } }Show answer
async function loadItem() { try { const item = await fetchItem(); return item; } catch (err) { logError(err); } } -
Match strategies to their uses
- try + await + catch
- Error in async function
- .catch(handler)
- Error in promise chain
- .finally(fn)
- Cleanup either way
- unhandledrejection
- Uncaught rejection