DEV Community

Aaron Powell
Aaron Powell

Posted on • Originally published at aaron-powell.com on

When a Promise falls in your app and no one is there to catch it, does it error? 🤔

Recently I was looking into monitoring static websites and it got me thinking about global error handling. There’s a good chance that you’ve come across the onerror global handler that’s triggered when an error happens and there’s no try/catch around it. But how does this work when working with Promises?

Promise Error Handling

Let’s take this example:

function getJson() {
    return fetch('https://url/json')
        .then(res => res.json());
}

// or using async/await
function async getJsonAsync() {
    const res = await fetch('https://url/json');
    const json = await res.json();
    return json;
}
Enter fullscreen mode Exit fullscreen mode

There are two errors that could happen here, the first is a network failure and the other is the response isn’t valid JSON (side note, fetch doesn’t return an error on a 404 or 500 respose), but we’re not doing anything to handle those errors so we’d need to rewrite it like so:

function getJson() {
    return fetch('https://url/json')
        .then(res => res.json())
        .catch(err => console.log(err));
}

// or using async/await
function async getJsonAsync() {
    try {
        const res = await fetch('https://url/json');
        const json = await res.json();
        return json;
    } catch (e) {
        console.error(e);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now we are handling the rejection and our application is all the happier for it.

Handling the Unhandled

In an ideal world, you’re handling all errors that an application may have, but in reality that’s not the case, there will be errors that were not planned for, which is why we have onerror. But, onerror is for handling errors that didn’t occur within a Promise, for that we need to look elsewhere.

Promises don’t error per se, they reject (which can represent an error or just being unsuccessful), and that rejection may be unhandled which will result in the unhandledrejection event being triggered.

onunhandledrejection can be assigned directly off window like so:

window.onunhandledrejection = function (error) {
    console.error(`Promise failed: ${error.reason}`);
};
Enter fullscreen mode Exit fullscreen mode

This is similar to onerror, but it doesn’t have quite as much information provided. All you receive in this event handler is the Promise that failed and the “reason” provided to the rejection. This does mean that you don’t get some useful information like source file or line number, but that’s a trade-off because it’s come from an async operation.

You can also call preventDefault on the error object which will prevent writing to console.error, which can be useful if you want to avoid leaking information to the debug console.

Handling the Handled

While you can capture unhandled rejections you can also capture handled rejections using the rejectionhandled event. While I find it annoying that it’s an inconsistent name (Rejection Handled to go along with Unhandled Rejection, why aren’t they consistent with where the word Rejection is!) this event handler works the same as the other one but will be triggered when a catch handled is provided.

This handler is useful if you’re doing a monitoring platform you might want to log all rejections, handled or not.

Conclusion

If you’re building an application you should always look to include global error handling. It’s very common to handle onerror but it’s quite easy to forget about global error handling for Promises and that’s easy to do with onunhandledrejection.

Top comments (4)

Collapse
 
stefandorresteijn profile image
Stefan Dorresteijn
window.onunhandledrejection = function (error) {
    console.error(`Promise failed: ${error.reason}`);
};

Please, please, please don't do this. This to me is exactly as bad as putting your entire application in a try, catch. You'll miss important errors and it'll make debugging a hell. Let your application crash, catch it with a good error reporting tool, and fix it. This is why we run betas and test often.

Collapse
 
aaronpowell profile image
Aaron Powell

You're right, you should have proper error handling as close to where you expect an error to occur and use a monitoring tool (which I blogged about recently) to capture unhandled errors.

The code illustrated in this post is just what these tools do, they attach to the global events like onunhandledrejection and onerror.

The point of this post is to show you how those work so you have a better understanding of just what is happening in the libraries you bring into a project.

Yes, you shouldn't capture a global event and just console.error it, you should do something constructive with it, but the code is for illustrative purposes. 😊

Collapse
 
pavelloz profile image
Paweł Kowalski • Edited

I almost missed that great article because i thought it wont answer the question made in title :-)

PS. It helps to have error tracking setup (ie. sentry, raygun) to also get notified about some obscure os/browser combinations that fail sometimes.

Collapse
 
aaronpowell profile image
Aaron Powell

So, did I answer the question 😉