Skip to content

Latest commit

 

History

History
26 lines (18 loc) · 791 Bytes

how_do_you_prevent_promises_swallowing_errors.md

File metadata and controls

26 lines (18 loc) · 791 Bytes

How do you prevent promises from swallowing errors?

To prevent promises from swallowing errors, ensure that you handle rejections using .catch() or use try-catch with async-await syntax. Additionally, always return or throw errors explicitly.

Example:

Promise.resolve()
  .then(() => { throw new Error('Error occurred'); })
  .catch(error => console.error('Caught error:', error));

async function asyncFunction() {
  try {
    await Promise.reject('Error occurred');
  } catch (error) {
    console.error('Caught error:', error);
  }
}
asyncFunction();

Tags: advanced, JavaScript, Promises