Happened to us on Friday. You shoulda seen the look of defeat on my coworker’s face. Looked like he was ready to give up software and become a goat herder in the Andes 😂
So what happened?
He’s performing a networking audit of our codebase. A large app we’ve built over the years. I built the first version in Backbone, then a team rewrote with Vue, then we all kind of contributed here and there.
And there’s been issues. Bugs so frequent users gave up reporting them. They just refresh and move on.
Well, our networking layer leaks errors like a rusty old bucket you find in the back of the shed. API throws an error, app flinches, shrugs it off, and moves on.
Users get undefined behavior galore. App thinks there’s data. There isn’t data.
It does! Except when it doesn’t.
Look at this code:
makeRequest method that always rejects its promise. An async/await version would throw instead.
Same effect. Promises make the mistake I’m talking about more apparent. You’ll see why.
Okay so you’ve got this function that sometimes returns an error. You try to be a good citizen, which means handling errors instead of blowing up your app.
You have a
getFirstItem method that calls the API and returns an item from its response. If there’s an error, it says there was an error.
All good, right? Job well done! You’re doing error handling and everything. So good.
Now look at this code, what does it print?
Think about it, I’ll send you the answer in 30 minutes 😛
PS: if you’re not that familiar with promises, here’s an old video I made in 2017 – a 2min explanation.
That’s right, it prints
You get an error from
getFirstItem. But then the error is handled!. The rest of your code carries on in the
.then chain like nothing happened.
And that’s how you build a leaky bucket without realizing it. Multiply that across months and years and many developers and well … 😅
The fix is to always re-throw errors. Unless you have a damn good reason why it needs to be eated.
With that tiny modification the code works as expected.
Yes the same rule applies to async/await code. You’re eating errors unless you explicitly re-throw.
Now go through your project looking for this mistake and try not to cry. 😛
Good luck and happy Monday
Learned something new? Want to improve your skills?
Join over 10,000 engineers just like you already improving their skills!
Here's how it works 👇
PS: You should also follow me on twitter 👉 here.
It's where I go to shoot the shit about programming.