DEV Community

Cover image for How to fix: Unhandled Promise Rejection
FailWarn
FailWarn

Posted on • Originally published at failwarn.com

How to fix: Unhandled Promise Rejection

Unhandled Promise Rejections occur when a JavaScript Promise is rejected, and there is no .catch() handler or equivalent
error-handling mechanism to manage the error. This can lead to unexpected behaviors, such as application crashes or unresponsive
features, especially in production environments where such issues can degrade user experience.

Common Causes

  • Missing .catch() blocks on promises.
  • Errors thrown inside asynchronous functions without proper handling.

Example

async function fetchData() {
    const response = await fetch('/api/data');
    const data = await response.json();
    return data;
}
fetchData().then(data => {
    console.log(data);
});
// No catch block to handle potential errors
Enter fullscreen mode Exit fullscreen mode

How to Fix

  • Always Handle Rejections:
fetchData()
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('Error fetching data:', error);
        // Implement fallback logic or user notifications
    });
Enter fullscreen mode Exit fullscreen mode
  • Use try...catch in Async Functions:
async function fetchData() {
    try {
        const response = await fetch('/api/data');
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching data:', error);
        // Implement fallback logic or user notifications
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Unhandled Promise Rejections can be a significant source of frustration in JavaScript development. By consistently handling these rejections, you can improve the stability and reliability of your applications.

Top comments (0)