DEV Community

Richard Shaju
Richard Shaju

Posted on

Stop Using Try-Catch: A Better Way to Handle Errors in JavaScript

JavaScript developers, there’s a new way to handle errors without relying on messy, repetitive try-catch blocks. Meet the Safe Assignment Operator (?=), an upcoming feature that promises to make error handling in JavaScript simpler, cleaner, and easier to manage. Let’s break down how it works and why it’s worth using.

The Problem with Try-Catch Blocks

Traditionally, JavaScript uses try-catch blocks to handle errors, especially in functions that involve async operations. But when you have multiple layers of try-catch, the code quickly becomes complex, hard to read, and harder to maintain.

Image description

The Solution: The ?= Operator

The new ?= operator provides a simple and effective alternative. Instead of writing separate try-catch blocks for each error, ?= lets you handle errors directly in one line. This keeps your code cleaner and easier to read.

Here’s how the ?= operator works:

  • It returns a pair of values: [error, result].
  • If an error happens, the first value is the error, and the second is null.
  • If there’s no error, the first value is null, and the second value is the result.

Let’s see how it simplifies our earlier example:

Image description

In this version, both network errors and JSON parsing errors are handled in a single line. There’s no need for nested try-catch blocks, making the code cleaner and more direct.

Why ?= is a Game-Changer for JavaScript

  • Cleaner Code: With ?=, you can handle multiple potential errors in a single line, without using extra try-catch blocks.
  • Centralized Error Handling: Instead of spreading error-handling code across different parts of your function, you keep everything together, making it easier to read.
  • Better Performance: With fewer try-catch layers, the code runs more efficiently.
  • Easy Async Handling: For async functions, the ?= operator lets you handle errors more simply without sacrificing functionality, especially helpful for APIs and web applications.
  • Before and After: A Side-by-Side Comparison

To see the difference, let’s compare the old way of error handling to the new approach.

Old Way (with try-catch):

Image description

New Way (with ?=):

Image description

See how much simpler the second version is? It’s easy to read and removes redundant code.

Looking Ahead: The Future of Error Handling in JavaScript
The ?= operator isn’t just a minor change—it represents a new, simplified approach to error handling in JavaScript. As JavaScript continues to evolve, tools like this help make it a more powerful, modern language for building web and server applications.

If you’re tired of cluttered try-catch blocks, give ?= a try when it’s available. It’s a straightforward tool that can make your code cleaner and your error handling much easier.

Top comments (115)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

This operator is a very long way from becoming part of the language, if it ever does. It's from a DRAFT proposal that hasn't even been accepted for consideration yet, let alone inclusion.

Collapse
 
bloodbaz2 profile image
Chris Walsh

Articles like this always seem to gloss over this point which is really annoying.

Collapse
 
raegen profile image
Nikola Pavlovic • Edited

Yeah and then there's the fact that, like all new ecmascript features preparing to land, it will be supported for years, by being transpiled into the fuckton of "try-catch layers" it's supposed to mitigate. For something that can be facilitated by a trivial utility function (well, a monad ideally), adding a new operator to the language is a completely deranged idea.
Not to mention that it would be quite confusing and typo-prone to have the actual token '?=' used in this way considering ??= already exists and is totally unrelated

Collapse
 
qianl15 profile image
Qian Li

Thanks! When I first read it I thought some new feature just dropped, and then I saw your comment 😂 The repo actually says, "This proposal will change to try-expressions as its a more idiomatic apporach to this problem." And they're looking for someone to help rewrite it...

guess there'll still be a long way to go.

Collapse
 
victor_gp profile image
Víctor González Prieto • Edited

Thanks for the heads up. 👍

Can you link the proposal? I can't find it... Or do you know the name they're giving this new operator?

Collapse
 
jonrandy profile image
Jon Randy 🎖️
Thread Thread
 
victor_gp profile image
Víctor González Prieto

Thank you!

Collapse
 
chani_diakidis_b2ab80f78f profile image
Chani Diakidis

I just wish that people stop using stop doing/using [placeholder].

Collapse
 
khuongduybui profile image
Duy K. Bui

Totally agreed. Just because there is a new alternative that is applicable in some use cases doesn't mean everyone should abandon the status quo.

Collapse
 
ozzythegiant profile image
Oziel Perez

That's modern React in a nutshell

Thread Thread
 
kbirgerdev profile image
Kirill Birger

Modern react is an oxymoron. React is a framework that is permanently stuck in some sort of dystopian alternate history universe

Thread Thread
 
adrian_zochowski_f7f740b2 profile image
Adrian Zochowski

Calling React a framework is like comparing a cat to a mouse. If you can't figure out that much, why even try to make any other comparison's.

Thread Thread
 
whosee profile image
whosee

There are many discussions about if it is or isn't a framework (in part because the definition of framework isn't clear cut). It is not as easy as citing what the react website says.

Thread Thread
 
adrian_zochowski_f7f740b2 profile image
Adrian Zochowski

So if the creator calls his cake "cheese cake" but you don't like it you will debate if its should be called cheese cake?

My understanding is that the react team never tried to create a framework, because there is literally no limitation to what you can do with react.

Compare it to Angular and you will find your answer. Debating if its a framework won't make you a better developer. Just assume what the creator intended for it to be, instead of trying to be smart when you're really not.

Collapse
 
jeydotc profile image
Jeysson Guevara

From the creators of "you're doing [placeholder] wrong" and "[placeholder-1] will change [placeholder-2] forever", Clickbaity studios! 🤣

Collapse
 
btsncollins profile image
Nathan Collins • Edited

It's one of the reasons I deleted my Medium account and now it's permiating here too.

Stop telling us what totally normal and absolutely fine thing is bad.

Collapse
 
kovesp profile image
Peter Koves

Maximally agree. I search for "Stop Using on this site, and got 50+ hits.

Collapse
 
josiahbryan profile image
Josiah Bryan

Why? You mean like for the returning another error or something? Not sure why that's a problem, honest question, just curious what you're thinking?

Collapse
 
return215 profile image
The Returning Soul

No, OP commenter meant to not use such phrase for clickbait article title

Collapse
 
dinma_zilla_4272b654a3e17 profile image
Dinma Zilla

The second example is somewhat confusing to read. The Try/Catch syntax is very intuitive. 👍🏼

Collapse
 
daemonbyte profile image
Robert Neve

It's very go-like syntax and it actually grows on you.

Collapse
 
magic_weaver09 profile image
Magic Weaver • Edited

great article! for anyone wanting to try a similar approach to the ?= operator now, i created safe-wrapper to handle errors gracefully. inspired by the safe assignment operator proposal, safe-wrapper returns a tuple [error, result] for both synchronous and asynchronous functions, reducing try-catch blocks.

it also includes type-specific error catching, allowing you to specify which error types to handle, throwing any unexpected types, for precise error management.

check out the npm package and give it a try!

Collapse
 
richardshaju profile image
Richard Shaju

Thanks for sharing

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Clearly the efforts made towards "centralizing" the error handling code makes it more complex and less intuitive than the try..catch version. While I see some value in this potential new operator, I don't think it is such a game changer.

Collapse
 
sti_selini profile image
Sti Selini • Edited

I do not, and never will, use nested try catch within a function. I almost never use it serially unless there is a massive reason such as immediate recoverability from the error, or state rollback, or a darn good logical reason, which is almost never.

I can count on two hands the number of patterns I've violated this rule with in JavaScript, Java, C++ and other languages in the last 35 years.

The reason you need solutions like this is you're writing bad code to begin with and have poor error handling design.

Collapse
 
patriziobruno profile image
Patrizio Bruno • Edited

You could have written the try-catch example in 5/6 lines of code, but decided to overcomplicate it just to make your case. Well done, I took the bait, this time 🙂 Another article like this and I delete my subscription.

Collapse
 
leob profile image
leob

What? This looks identical to a post that I saw on dev.to a few months ago - why and how is this being "recycled"? Besides, this isn't even an accepted proposal, let alone it's implemented in JS already, so it's misleading to say "stop doing this or that" when the alternative doesn't even work ...

Besides, people should stop writing article titles like "STOP using this ..." or "you MUST do that ..." - we're not toddlers, we can make our own decisions and trade-offs, rather than being patronized or being told what we "must" do (even more so when the actual information is inaccurate or misleading) ...

How and why did this article make it to the top of my "dev.to" feed? Pretty useless ...

Collapse
 
ctsstc profile image
Cody Swartz

You could give a library like TS Results or Never Throw a try which gives additional tooling and abstractions that provides some quality of life & niceties, which can be used right now.

Given that this is not currently implemented for LTS I would recommend an abstraction like a library which could later utilize this method under the hood if/when it makes sense.

Collapse
 
_c2fc0b323bf profile image
Sergei Kostov • Edited

I made an account just to write this!

How can I down vote this. What an awful idea! This is going backwards. This is de-evolution. Degradation. Only people who have never in their life had to program in a language who has no exceptions may propose things like this.
Stop it get some help!