Async Error Handling
Use try/catch inside async functions, or attach .catch() to the returned Promise. Both are equivalent — choose one style per function.
Use try/catch inside async functions, or attach .catch() to the returned Promise. Both are equivalent — choose one style per function.
// try/catch style
async function fetchData() {
try { return await api.get("/data"); }
catch (e) { if (e.status === 404) return []; throw e; }
}
// Caller with .catch
fetchData().then(render).catch(showErrorBanner);
// Helper for safe awaiting
const [data, err] = await fetchData().then(d => [d, null]).catch(e => [null, e]);
The [data, err] tuple pattern (like Go) avoids nested try/catch without losing error context.
More in JavaScript