JavaScript developers, there’s a new way to handle errors without relying on messy, repetitive try-catch blocks. Meet the Safe Assignment Operator ...
For further actions, you may consider blocking this person and/or reporting abuse
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.
Articles like this always seem to gloss over this point which is really annoying.
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
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.
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?
github.com/arthurfiorette/proposal...
Thank you!
I just wish that people stop using stop doing/using [placeholder].
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.
That's modern React in a nutshell
Modern react is an oxymoron. React is a framework that is permanently stuck in some sort of dystopian alternate history universe
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.
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.
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.
From the creators of "you're doing [placeholder] wrong" and "[placeholder-1] will change [placeholder-2] forever", Clickbaity studios! 🤣
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.
Maximally agree. I search for "Stop Using on this site, and got 50+ hits.
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?
No, OP commenter meant to not use such phrase for clickbait article title
The second example is somewhat confusing to read. The Try/Catch syntax is very intuitive. 👍🏼
It's very go-like syntax and it actually grows on you.
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, reducingtry-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!
Thanks for sharing
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.
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.
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.
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 ...
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.
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!
My take on this is that most code has to many try catches anyway. The example above could have been just one try catch
The file successfully loaded or not. The reason why it failed, a file load failure or parsing becomes clear from the error stack trace.
On the safe assignment operator itself. I kind a like it but not convinced it is a game changer
I am unsure how this makes the code simpler .
Often you want to propagate thrown errors to previous layers of code, ending up with a top level error handler
It seems this approach will require you to deal with the error where it happens, which will lead to MORE lines of code, and spreading of the error handling logic.
What am I missing?
How is this better? Proper use of try catch results in clean code because you have zero error handling in your main code - it’s all at the bottom making the happy flow easier to read. Your example is just bad try catch usage and one can easily imagine bad usage of the new operator where you end up with an if after every command - the whole reason exceptions were invented.
Try rust
Here is a better article to read about
[the same concept](dev.to/polakshahar/stopping-errors...
FWIW, language features like this are super fun, but as Jon Randy points out, not in the spec - and in this case, it is very unlikely to ever be accepted, as try expressions looks more likely to be the solution to block-based try/catch. I'm sure you'd get less push back if you changed the title of this article to something less clickbait-y like "exploring the ?= operator in javascript" or "how to use experimental safe assignment in javascript".
For those interested in more context, here's the proposal (note the author's warning at the top):
github.com/arthurfiorette/proposal...
Here's the larger discussion: github.com/arthurfiorette/proposal...
FWIW the proposal that (at the time of writing) looks most likely to make it into the language is actually a new
try
operator that works during assignment:It's somewhat similar to your article above, so perhaps a note that we're likely to get this functionality in typescript and later ECMAScript somewhat soon, but that the operator itself is still being discussed. And of course, if you have strong opinions, join the discussion and voting on the proposal thread!
To everyone reading this, it is a proposal and the "?=" operator more than likely won't be used, because it too close to nullish coalescing assignment. The more agreed upon solution (currently) is something like:
See the draft: github.com/arthurfiorette/proposal...
Scott
Those two pieces of code are not equivalent, in the first you are distinguishing between the two different errors while in the second you aren't (and can't anymore, you've lost that information).
If you don't care about detecting different errors but just any error then the first example becomes just as simple as the second one.
In fact if you have more complex code with multiple places that can generate errors than the try-catch becomes simpler again because you could have a single try-catch block instead of needing if-statements for each.
So the operator might be nice in some circumstances (especially in JavaScript where most errors are untyped) but I don't see any real advantage, only a stylistic choice.
I don't think this will be a game-changer. It looks similar to Golang syntax but without a
defer
function, the one of important parts of error handling in the Golang world.Golang example:
Actually, if you are using typescript, you can do something like this:
It's used in my recent project and is more readable for me.
This syntax is awful, too. An assignment operator right in the middle of the ternary operation? Just awful. Gotta be a joke.
I thought the reason is dangerous , if it's about readability haa check how spaghettish Java is 😆😆😆
Don't get me wrong am not criticizing your article. Infact I love it. Am just justifying how this operator could not be ideal
My opinion 🤣🤣
I like the approach, because I hate the multiple inners try,catch,if,else,etc.
Based on this, I wrote a basic function:
you can use it like this:
this is very similar to Go approach, which has (at least) one major flaw: you can not "catch them all" - if you have multiple statements which can throw an error and you don't really care which one of them does (like you need to immediately stop the entire execution), you'd need to flood your code with nested
if (err) { ... }
. even in short one-liners you'd still have to replace thetry...catch
with anif
, so it does not really make the situation any better, reallyIt's a bad example in the first place because you're just recreating built-in error handling, but if you really needed something like that:
Promise.try
isn't supported in Safari but you can either polyfill it, or usenew Promise(r => r(JSON.parse(...)))
What a strikingly modern approach!
I remember this kind of advice from the start of my IT career in the 1970-s.
"There is a return code from every system call. Be sure to check it after each call and take appropriate action if an error is indicated."
Mind you, when code was presented in articles like this, the error handling was omitted for clarity.
Stop using clickbait to waste my time.
Please avoid using clickbait that wastes readers' time. Clearly state at the beginning of the article if it is a proposal, so readers don’t have to sift through comments to discover this only after investing time. While well meant, with limited time and attention, articles like these can be really frustrating.
omg, besides the point that this is not even in consideration yet, in what world two messy ternaries like that are better than the organized try catch? it's not like I like the try catch, is just that this new operator seen a lot worse
This is impractical beyond belief.
You are now writing extra code for conditions which should never occur.
If there's a readError, you should not ever get to the code that would generate a parseError. That's what try catch achieves. It may feel unwieldy, because of the nesting, but in this example it is more effective and manageable.
You could simply use try-catch to provide the same pattern of returning an error object instead of a result from the function that reads a file.
See: fantasyland, result pattern, either pattern
Seealso: fp-ts, purify-js
Creative approach, if using try-catch statement just for one-line code like "just" fetching URL or open file etc etc, its a good way.
Try-Catch still used to handle many statements, fetching URL, parsing JSON, save or update to DB, or forward response to another URL.
Just like ternary operator, bool ? If-true : if-false, it's good to handle one-line statement.
Anyway, this is good thread, new way to handle things is one of the best part of programming 🍻🍻🍻
I don't agree here.
First of all it is not in the language yet.
Second, the definition of the problem is dubious. If you have many nested try-catch block there is something wrong with your code and new syntax isn't going to fix it.
Third, what is the performance claim based on? Have you done any research?
Fourth - the claim try-catch does not fit with async operations. I would say rather opposite is true. With ?= operator you would need to throw an Error if you want rejected promise. Not every time you need to handle the exception right away, you probably want to defer the error handling and do it elsewhere.
Fifth - your after example is perfectly achievable with a single try-catch block.
Jumping the gun a tiny bit here with this article? 😆 The syntax isn't even correct, bro. The proposal has moved on to try expressions instead.
I think you should take this down. Or at least make it abundantly clear that this is not anywhere near decided. I'm fact, almost the opposite.
Not to mention the amount of unmentioned drawbacks of this anti-pattern. You can explore a lot of the drawbacks in the issues of the GitHub repo for the proposal.
For anyone reading. Do not take this trigger-happy author's word for it, and I recommend not trusting anything else they write in the future. 👍
that is a bad example of nested
try catch
block, you could use singletry catch
block to catch both errors, and justconsole.error
it, the error message should be self explanatory to which one causing the errorWhy not separate the functions into their own blocks?
Why not just follow best practices and SOLID principles and:
"Because that's writing more code?!? ", and it has a purpose, but I'll leave that to you, dear reader.
Be well
So we have to check if each and every error exists with the new method?
Now suppose you have 10 methods which can throw an exception, do you include each and every error variable in switch case or something?
Old way is cleaner and efficient
This is officially the last time I read an article that starts with any of the following phrases:
I'm old enough, and been in the practice long enough to 'Know' better...
Know the argument will be marginally coherent,
Know support for the premise will be thin, subjective, self-serving, or just plain wrong,
Know I'm going to read about a 'new' solution that was actually conceived, tried, and abandoned with cause prior to the college years of the poster,
Know the comment stream will include:
The OP did nothing specific to be the example I'm making of them, it could have been any of hundreds of other posts within the last 24 hours.
I only make my stand here because I literally debated with myself for upwards of 10 minutes before clicking through what I was sure to be click bait. It was just luck of the draw.
readFile(...)
.then(data=>cfg=JSON.parse(data))
.then(runCode(cfg))
.catch(alert("an error") ;
You can use Promise syntax (but that is causing some other problems).
You can use try-catch (preferably dividing your code into smaller pieces).
You could use whatever unofficial extension that you create a polyfill for. Like "?=" which is not yet supported.
JavaScript has the flexibility of not using types (though you could use typescript, jsdoc and even check types during runtime). It offers multiple ways to solve different types of challenges - you just need to pick the best for your case and know what are the consequences (you sacrifice something to gain other thing).
I would not tell "don't ever use this feature". However I could list pros and cons of some features. I encourage you to look wider and check whether there are niche scenarios that could fit other options (or maybe your case is the niche?).
Is it a clickbait repost, or what?
It looks like a newly re-generated version of this post: dev.to/paharihacker/effortless-err...
This is wrapping exceptions into old style return code errors. It's reliving all the mistakes of the 80s. The resulting code looks just like return codes, and then uses a contrived example of bad exception handling to make exceptions look worse. They each have their tradeoffs, but return codes nearly always result in more code.
"...It's reliving all the mistakes of the 80s..."
Amen, brother.
The pendulum never stops swinging, does it?
This tries to do for
try-catch
whatawait
did for async callbacks. But it misses a few significant points:finally
block harder to implement.await
** solved async 'callback hell' - whether in promise chains or node-style callback functions - which is typically a non-issue with sane, un-nestedtry-catch-finally
.catch
block (with possibly error-specific handlers within - but only when necessary.)Incidentally, all the above goes for the similar
try await
proposal. Different syntax, same ramifications.I've been on this pendulum before - I'll pass.
**
Await
isn't without its tradeoffs, either, BTW. Central among them is the inability to pass a 'future' (aka Promise) around for separate inspection and effects handling by decoupled code. Think pub-sub. But it also suffers the one-test-per-await problem above. Ironically, the best way to stop a sequence ofawait
s on error is wrapping them in atry-catch
block!Another article in which the autor ditches on a topic in favor of a "NEW STILL NOT SUBMITTED PROPOSAL", claiming that is the new game changer.
PLEASE - stop producing this kind of garbage - people end trusting you.
OR - write it as it is: "there is a guy with an idea, this is the github project pahe with his proposal still in draft that..." and you explain what you are referring to and your excitation for the topic.
BUT passing the thing as if it was already in the JS spec is a clickbaitish strategy
OR it could be a strategy to spread the topic and get more people pushing for its proposal - idk
TO ME: I'm reporting this article as scam.
I can't get it together please help help me here , so based on this article , the async functions returns array now for destructuring ?, If it is why the '?' before '=', I think this '?=' Is bit far, cause even we use '?=' We have to wrap the logic under an if condition like they explained above in the example . Normally '? ' represent ' likely if ' for eg Ternary operator .
I know I am not that much of developer , so please hammer some reason behind his into me thanks in advance.
Iam sorry if I used harsh words, cause Iam new to comment, I'm still learning.🙏
If each type of error is handled the same way, by logging for example, this operator makes the code cleaner. But if there are different recovery responses for different errors you would need if-then or if-then-else or switch statements, so, not cleaner.
If developers would stop using errors for control flow you wouldn't need this crap scattered throughout your code in the first place. Maybe next time, at least wait until it's supported in Typescript - then it'll be widely accepted as a standard as it will be past Stage 3.
This is what happens when the third world starts trying to code.
Can't tell you how many times we've had to throw away code that some third worlder visa recipient contracted from his home country of third worlders, millions of dollars wasted, for Americans to clean up the mess.
Get out of here with this junk
Such a misleading and shitty article
Actually, you could remove the nesting try/catch block and wrap the whole code with one try/catch block.
Feels a little like on error resume next in the very old days of VB. If I don't check the error variable my code keeps running? Source of a lot of dangerous bugs.
const [parseError, config] = fileContents ? JSON.parse(fileContents) ?= [new Error("No file contents"), null];
Can you explain what this ? after fileContents is doing here?
try ...catch ... finally is a proven statement. Messiness is just a relative term. From my experience, I am sure this operator can be a complement but not a replacement, at least for now.
I personally don't have any interest to replace try catch with it, but glad to see other perspectives.
Nice article!
I wonder if there will be a performance penalty for using this like try catch has. If there isn't I would definitely be using the syntax. But I'm pretty sure like all new language features the engines have difficulties optimizing it over older and more well-known syntax. Ultimately I think this is just going to be syntactic sugar with the same caveats the old way of doing it.
I'm sorry, but the example is lame. The nested try/catch handles a pair of errors differently, where the ?= example handles them as one. The original try/catch could have done exactly that by removing the inner try/catch.
Depending on the situation, I will sometimes nest the try/catch just to adjust the thrown error or to do some logging, and then re-throw. In my case I am writing server code and one error may be a 400 while another is a 500
It resembles Golang way but written quite awkwardly. Typically it should handle potential errors returned and terminate execution if any, then, proceed further.
This is neat but readability is lost. The try/catch flow is vertically longer but it’s so much easier to follow. Expecting people to know that this operator somehow makes js into golang is going to confuse more people than it impresses.
it's better to use libs such as await-to-js imho
Or learn to write cleaner code, without nested try catches.
using await-to-js you are actually writing more cleaner and readable code without nesting try catch, is like using await/async instead of promise hell you cannot write code without handling various exceptions for sequential operations which the next one depends on the result of the previous one, othwerwise I don't understund your comment
My point is, in my opinion, if you find yourself needing a nested try-catch, you should take that as a hint to a needed refactor. Pull that code out into a separate function. Cheers
Stop with the clickbait already. So annoying to see things that you can’t implement 💩🤬
Stop using try-catch => use something that not exist yet instead. Are you sure you understand how this world is working?
It's like someone saying "You've been using the can opener the wrong way!" ..."Stop that, do this."
Oh no 😵
I have a strong feeling this article is purely AI generated. Maybe i'm wrong. And if there is one term that screams AI to me, it's got to be
game-changer
. I'm honestly sick of that term. :DYour writing is always engaging! I'd also like to recommend EchoAPI for JavaScript projects. It has truly enhanced my development experience, providing powerful tools for efficient API management.
I like it, ignore the doubters. Try/Catch is sloppy.
I'm not sure where you got the examples but your if else is worst than the try catch itself. I suggest you learn basics first.
This reads like an AI rewrite of other articles I've read with near identical headlines.
I really don't see the point of this new syntax. It just puts all your code in one line, I don't believe it's as neat as try/catch and I can see it becoming very messy in the long run.
nice option 👍 thanks for the article
but it looks a little bit "unmaintainable" for me.
I think it's best for singular functions. It's hard to read big codebase with something like that. Really, depends on your app. Always keep the niche in mind.
It simplifies the structure but increases difficulty in readability
Guys, please do not stop using "try" and "if" operators, stop using ?=?:@#$*!~ and all of that stuff. Humans try to read your code and fail.
Inspired by go?
No, in Go we use bulletproof "if" to check error)
If you are interested in knowing more about the proposition and its current limitations : github.com/arthurfiorette/proposal...
Is it deopt in v8? Try catch where optimized not that long before and its flaweless interesting how this behaves in performance critical code.
Not for me, sorry.
No, it’s not easier to read. It’s just a different way to note down the same thing. I don’t think the second example solves any problem.
Yeah, let's replace the simple try - catch with another hook logic. Perfect. Just what I needed.
Which browsers support this operator?
This feature is not yet released
Have you read the proposal? This syntax is deprecated, and the proposal is far away from be implemented in the runtimes. So this article has no value.
This is neat! I haven't done much with try-catch in JS (I'm moving more towards Python), but this is cool. Is there a more efficient way to do this without having to define tons of variables?
Would be nice, but it doesn't exist today.
Are we just gonna ignore that you didn't await the fetch before requesting the json body?
This is what golang was criticized for 😅 especially from some js devs.
Now you have to set the initial state of every error type before youll see the error. How is this better?
Thanks for sharing. Keep it up 👍
It may be helpful but it will really be hard for the new beginners
Nice to know!
Looka like dynamic proxy and centralized interceptor...nothing fancy
Why can't we simplify the code into smaller modules and then use try catch in each modules? That will be more readable i guess.
i wish the Internets add the dislike button again so we can down vote this article for not saying that this is experimental
Nice ❤️
Less typing just a progress.
Another junior developer.
I am not sure what was your point.
Totally Agree
Kinda like error handling in Go. I might be wrong thou