I'm Ditching Try/Catch for Good!

preview_player
Показать описание
The try/catch block is a staple of JavaScript, but it leaves a lot to be desired (especially when working with TypeScript). None of the errors are typed, it adds an extra level of block scoping which can make certain code difficult to write, and it catches all errors (not just the ones you want). That is why in this video I will show you 3 alternatives to try/catch that I much prefer.

🌎 Find Me Here:

⏱️ Timestamps:

00:00 - Introduction
00:24 - Starting Code
01:12 - Bad Error Handling
03:36 - Basic Fix
06:11 - Advanced Fix

#ErrorHandling #WDS #TypeScript
Рекомендации по теме
Комментарии
Автор

How come you ditch everything every week?

saturn
Автор

I don’t buy it… you can just put try catch on separate sections … just keep it simple

moonwhisperer
Автор

We’ve come full circle; ditching try/catch for .then().catch() 😆

clevermissfox
Автор

It's interesting for sure. Although I think all we've really done here is inverted the try-catch.
You're still handling the error at the top with if(error), and the else block is like the old "try"

risitas
Автор

in my opinion this is not the best advice, because this is idiomatic with Go where it forces you at a langauge (& LSP) level to consume the error returned in some way but forcing this idom into typescript - which dont get me wrong i have done similar in the past as well - risks inconsistent implementation which means error states not interupting the control flow in the right way at the right times.

Forcing idioms doesn't always make sense even if they yield nicer syntax.

EDIT: Also worth thinking about the several ways that error propagation can 'escape' the promise chain depending on what async you're doing (not just promise based), whether its unawaited+not returned, using timeouts that aren't themselves promise wrapped and awaited etc, which would make your errors evade your generic catch block, ending up probably at the process level or at least far away from its lexical context. Then you're either doing a bunch of nested calls to your wrapper, or just doing some nested .catch or even worse relying on process.on() captures, or something else depending on context, which ends up with a messy mix of paradigms.

Imo it's just better to stay within the language idioms for predictability. Just my opinion though. If you want to write in languges that reliably return errors, and force you to consume those errors, use those languages. Typescript might have foibles in errors particularly in some async operations but this just seems like asking for trouble in production code.

In other words, idioms exist in langauges in the context of how that language operates. Just because you can replicate and 'paste over' 90% of the behaviour through functions in another language, does not mean that you should. That missing 10% is going to cause hella problems and if you work in a consequential domain then that's not really a good idea, just for the sake of some opinionated preference on syntax.

Just learn async really well, learn the event loop, handle it all idiomatically, and you're golden.

chriskennedy
Автор

we don't talk much about Effect, this lib is impressive

notoavinarazafilalao
Автор

3:00 that isn't the only way to deal it it. You can use tools like "instanceof" in the catch to determine what type of error was thrown and deal with them in different ways just like you ended up doing it in a convoluted way.

pomprocks
Автор

If you have small functions which only do one thing, then you won't have a bunch of code tryign to interact with your user right there immediately after you fetch it. Your try catch can just be in the fetchUser function.

EricSundquistKC
Автор

This is how go handles errors by default, very pleasant

pu
Автор

The catchError funcion is exactly what golang does.

I tried to introduce that in a previous job and I got so much push back that I had I to remove all of it.

The only annoying thing is that, unless you use let, if you have multiple of those calls I the scope, you'll have to name the error const something different in every call.

ericmackrodt
Автор

Why do i need try catch nesting? Because error.message tells what is the problem with the code. Its not like it shows completely unreadable error.

Takatou__Yogiri
Автор

I prefer "withCatch" as name to tell it is a wrapper

alii
Автор

This doesn’t make sense. We have built ins for this. Use a try/catch and rethrow the error. You can provide a cause in the options if you want access to the original. In TS you can cast the error as unknown and you’ll be forced to check the type too. Sure abstract that into a function if you want something reusable but use the languages patterns and conventions

samjohnston
Автор

It’s fascinating to explore this possibilities, but I strongly recommend sticking to the try-catch approach 99% of the time, reserving the techniques discussed in this video for a few highly specific cases.

Gabriel-iqug
Автор

The correct solution is to try catch the fetch statement and return undefined if it fails instead of the user data.

What you're suggesting instead is a hacky version of a callback statement from the era before promises. We moved past that for a lot of good reasons. One of the problems you are going to face is if you do this twice in the same block of code and now have two variables named error. So now you're naming your errors things like error1 and error2? What is this recommendation.

nathanl
Автор

You can simply add add bracket for the let scope variable.

Try catch not meant to catch all error except the outermost one. You catch known errors and handle it accordingly.

If you comes from Java you know that's well how Try/Catch is suppose to work. The exception is try/catch need to carefully handle the asynchronous situation.

sfalpha
Автор

An interesting approach but perhaps this is fixing smth that isn't broken?

Smoljames
Автор

"Ew, we have to move things into this try/catch. That's too much work!"

/proceeds to write a complicated generic function that mixes results with operation state

johnlagnese
Автор

"try and catch" role is to catch Exception, "unexpected behavior" like network loss, i/o problems, etc.. Not for typo or error made by developer.
In PHP, if you try to print_r() a undefined variable, it will raise an Warning error. In Java, because of compilation, your code would not even compile at all because to try to do something with undefined variable.
In JS, in your example, it will failed because your variable is defined in the scope of the "try and catch" ... again, it's a language feature ...
So, the problem here are about the pro and cons of how scopes are generally handled on the language level (just compare php/js/python per example).
Until TypeScript become a real language on its own, you'll have live with the fact that is JavaScript is behind executing it ...
But, I love it for what it offerts :)

PepereWorld
Автор

Effect also has an "effect/Micro" component that seems like a reasonable choice if we're mostly trying to get the benefits of the core Effect type and not all of the other powerful offerings that come with the full library. I'm still getting a feel for Effect since fp-ts announced the merger with it.

rufio.tf