
Digiaru started this conversation 1 week ago.
Unhandled Promise Rejections in JavaScript / Node.js
I have asynchronous code using Promises or async/await, and sometimes errors are not caught—leading to silent failures or warnings such as UnhandledPromiseRejectionWarning. How can I prevent this?
Kar
Posted 1 week ago
Unhandled promise rejections occur when a promise rejects and no .catch() or try/catch block handles it. These silent failures can crash apps or cause unpredictable behavior, especially in production environments.PixelFreeStudio Blog -+9Medium+9Reddit+9 Common mistakes: • Forgetting .catch() on promises • Throwing errors within async code without catching them • Failing to return promises in promise chains, breaking the chain and skipping error handlingDEV Community+1InfiniteJS+1 Fixes: • Always attach .catch() after promises: js Copy code fetchData() .then(data => …) .catch(err => console.error(err)); • Use try/catch with async/await: js Copy code async function fn() { try { const res = await fetchData(); } catch (err) { console.error(err); } } • Handle global rejections: js Copy code process.on('unhandledRejection', err => { console.error('Unhandled rejection:', err); }); • For concurrent tasks, use Promise.allSettled() to avoid failing the entire group on one rejectionDEV Community+3InfiniteJS+3Medium+3Medium+1Just Program It+1Reddit+2The Linux Code+2Just Program It+2PixelFreeStudio Blog -+1InfiniteJS+1