How can I use custom errors in asynchronous JavaScript (e.g., Promises)?

Responsive Ad Header

Question

Grade: Education Subject: Support
How can I use custom errors in asynchronous JavaScript (e.g., Promises)?
Asked by:
72 Viewed 72 Answers

Answer (72)

Best Answer
(317)
In Promises, you can `throw` an error within the `.then()` or `.catch()` blocks. The `catch` block will then handle the error. For example: `fetch('/api/data') .then(response => { if (!response.ok) { throw new Error('Network error'); } return response.json(); }) .catch(error => { console.error(error.message); });`