I'm Ditching Try/Catch for Good!

  Рет қаралды 191,415

Web Dev Simplified

Web Dev Simplified

Күн бұрын

Пікірлер: 701
@567saturn
@567saturn 2 ай бұрын
How come you ditch everything every week?
@svens3722
@svens3722 2 ай бұрын
hes dutch
@koruko634
@koruko634 2 ай бұрын
@@svens3722😂
@theankushgautam
@theankushgautam 2 ай бұрын
​@@svens3722 😂
@Saint_Crocodile
@Saint_Crocodile 2 ай бұрын
Well he has to run a youtube channel 😅
@PraiseYeezus
@PraiseYeezus 2 ай бұрын
This was also my reaction when I discovered there was this weird concept called "learning" that lets you find new strategies that you like better than your old ones.
@moonwhisperer4804
@moonwhisperer4804 2 ай бұрын
I don’t buy it… you can just put try catch on separate sections … just keep it simple
@caribouroadfarm
@caribouroadfarm 2 ай бұрын
Not only that you can have multiple catch clauses for a try clause.
@genechristiansomoza4931
@genechristiansomoza4931 2 ай бұрын
Usually the controller is the best place to put try catch
@Kriszzzful
@Kriszzzful 2 ай бұрын
@@caribouroadfarm You can? I just checked MDN and didn't find it, can you post a link? Or do you mean multiple if/else in a single catch block?
@vagkalosynakis
@vagkalosynakis 2 ай бұрын
No dude, you're supposed to work differently to how the rest of the industry and your team works, you don't get it! /s
@caribouroadfarm
@caribouroadfarm 2 ай бұрын
@@Kriszzzful I don't know if you can post links here, but those things called Conditional catch clauses just google it
@clevermissfox
@clevermissfox 2 ай бұрын
We’ve come full circle; ditching try/catch for .then().catch() 😆
@moligun83
@moligun83 2 ай бұрын
That's what drove me crazy: async/await is syntax sugar that produces the exact same Promise. The error handling function could have easily been written as an async function with a try/catch block.
@dio56301
@dio56301 2 ай бұрын
yeah, was thinking the same (that it could be rewritten to async try/catch) ... so what am I missing here?
@gohancomfejao
@gohancomfejao 2 ай бұрын
Yeah it’s the exact same thing, but this creates reusable functionality. Otherwise you’d have to reimplement the same function for everything that handles promises.
@thescientisthorse
@thescientisthorse 2 ай бұрын
I get "callback hell" vibe
@WhiteVanyo
@WhiteVanyo 2 ай бұрын
@@dio56301 I doubt you're missing anything other than preferences. I can say, when I first started coding try {await x()} catch {} was easier to write and understand than .then(). That being said, this methodology in the video is fascinating and I will have to give it a try.
@johnlagnese7076
@johnlagnese7076 2 ай бұрын
"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
@johnridout6540
@johnridout6540 2 ай бұрын
It's actually a very simple function. Here's a pure JavaScript version. const catchError = promise => promise .then(data => [undefined, data]) .catch(error => [error])
@josephvictory9536
@josephvictory9536 2 ай бұрын
@@johnridout6540 Yes, im thinking of implementing this right now. I was quitely annoyed at the try catch situation i had before and this is a good solution.
@chris94kennedy
@chris94kennedy 2 ай бұрын
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.
@amineabdz
@amineabdz 2 ай бұрын
it's a different perspective, it makes it a little bit easier to write the flow of the logic without try catch, but you would need to handle the error flow yourself
@chris94kennedy
@chris94kennedy 2 ай бұрын
@@amineabdz i think you're missing what im putting down
@jsvrs
@jsvrs 2 ай бұрын
it's hard to read. try adding some line spaces.
@chris94kennedy
@chris94kennedy 2 ай бұрын
@@jsvrs fair enough, have done so
@justsomeguy8385
@justsomeguy8385 2 ай бұрын
I somewhat agree. It's still JS, and as long as you can enforce this pattern using a linter rule and CI job, any developer who isn't completely useless can learn the pattern intuitively in literally an hour.
@risitas5874
@risitas5874 2 ай бұрын
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"
@ojikutu
@ojikutu 2 ай бұрын
We've also managed to escape the variable scoping of try-catch
@Blafasel3
@Blafasel3 2 ай бұрын
And you can do an early exit on the error. One issue with try catch is that it inverts the exit early pattern that is very common place.
@risitas5874
@risitas5874 2 ай бұрын
@@ojikutu Not really because he's basically just moved the scoping to the else block. You wouldn't want to access the user variable outside the else block anyway
@lilyydotdev
@lilyydotdev Ай бұрын
@@risitas5874 That's literally not how scoping works or what that means. Besides, as he also pointed out in the video, the only reason he is using the else block at all is because he was not inside of a function and could not early-return.
@notoavinarazafilalao7415
@notoavinarazafilalao7415 2 ай бұрын
we don't talk much about Effect, this lib is impressive
@eprd313
@eprd313 2 ай бұрын
What do you use it for mostly if I may ask?
@notoavinarazafilalao7415
@notoavinarazafilalao7415 2 ай бұрын
@@eprd313 Honestly, I'm not fully using it in my codebase yet, but you can watch Lucas Barake's videos with some cool examples
@PeterSahanaya
@PeterSahanaya 13 күн бұрын
@@eprd313 I use it just for error handling on my Next.js app, it's cool i can catch specific error, i use it a lot on server actions
@pomprocks
@pomprocks 2 ай бұрын
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.
@RmonikMusic
@RmonikMusic 2 ай бұрын
Agreed. The only thing he's solving is not having to define the variable as a "let", using a "const" instead. But a const with extra type checking after is infinitely worse. Besides, if you write proper functional code, you usually want to return the value at the end of your try block, in which case you can just assign the value to a const wherever you wanna call the function. So in reality, the situation he's trying to solve it not even a valid one.
@ericmackrodt9441
@ericmackrodt9441 2 ай бұрын
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.
@krtirtho
@krtirtho 2 ай бұрын
Once a wise man said, "Don't bring one language's convention in another language"
@Nguyen-c7z
@Nguyen-c7z 2 ай бұрын
Cause it's honestly stupid. No proper developer write try catch like that anyway. This is junior example.
@chris94kennedy
@chris94kennedy 2 ай бұрын
it is *not* exactly what golang does.
@ericmackrodt9441
@ericmackrodt9441 2 ай бұрын
@@chris94kennedy Sure, it's not native to the language, and golang doesn't return an array, it can return multiple values in the same funcion. But in terms of flow, it's pretty much the same.
@chris94kennedy
@chris94kennedy 2 ай бұрын
@@ericmackrodt9441 no - it is not. Please go and read my main comment on this video where i lay out why this is not the same - despite *looking and feeling the same in many/most cases* as golang.
@alii4334
@alii4334 2 ай бұрын
I prefer "withCatch" as name to tell it is a wrapper
@dmltdev
@dmltdev 2 ай бұрын
Do you mean something like that? function withCatch(fn, errorHandler) { try { const result = fn(); if (result instanceof Promise) { return result.catch(errorHandler); } else { return result; } } catch (error) { errorHandler(error); } }
@dmltdev
@dmltdev 2 ай бұрын
Misunderstood at first. Disregard pls.
@MerthanMerter
@MerthanMerter 2 ай бұрын
i prefer $catch
@4sxS307cAW
@4sxS307cAW 2 ай бұрын
i prefer create a catch factory. we are not the same.
@Gabriel-iq6ug
@Gabriel-iq6ug 2 ай бұрын
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.
@goosybs
@goosybs Ай бұрын
Why though? There a huge library building on this concept (EffectTS) and golang does this already by default. Also the inconvenience of try/catch is one of the two reasons why people still write: data = await fetch(...) result = await data.json() This should throw a compile error and be red in your editor, but it isn't. JS/TS should know that this throws atleast 2 errors and expect you to handle them. There's even a TC39 proposal to add this as a new keyword (behaviour). While it doesn't solve the issue that the language doesnt know what could throw (EffectTS solved this as best as it could), its still very encouraging to actually handle errors properly with this. So i'm really interested in why you would not recommend it...
@EricSundquistKC
@EricSundquistKC 2 ай бұрын
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.
@Jajoo13
@Jajoo13 2 ай бұрын
But then you have to somehow tell in the return value that what you returned is coming from an error. I know you can let this slip sometimes but this approach can't be used universally. For example - say I have a method that gets something from the server and this something is an array of some items. Yes, you can always pass an empty array as a fallback but that does not say anything about the way of getting the data. What if you want to let user know that there's been an error getting the data and that's why they're seeing an empty list? Sure, you can display the message in the try/capture block of this method but unless you have some kind of centralized error handling, most times this will not be the case.
@Smoljames
@Smoljames 2 ай бұрын
An interesting approach but perhaps this is fixing smth that isn't broken?
@Jajoo13
@Jajoo13 2 ай бұрын
This is no fix - it's an improvement over standard try/catch.
@francescolasaracina3964
@francescolasaracina3964 Күн бұрын
​@@Jajoo13 ​Not really an improvement because you still need to implement a series of if clauses just to handle different types of errors, a thing that you can already do in a more readable, flexible and extensible way using multiple catch blocks. The only improvement I see over the try catch situation is to use a more functional programming style approach that involves the use of some kind of Maybe monads and the like
@samjohnston88
@samjohnston88 2 ай бұрын
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
@chris94kennedy
@chris94kennedy 2 ай бұрын
thank you for a sane comment. use the idioms that exist in the language because those idioms rely on the underlying mechanics to actually make sense. Just because you can get 80-90% of the way towards replicating a language behaviour from go in typescript does not mean you should, there are many ways this guy's code is going to go wrong. See my main comment for detail. It's sad to see a so-called senior engineer promote this imo because half the comments are like 'wow thats amazing im going to adopt this'. Enjoy the footguns.
@Kriszzzful
@Kriszzzful 2 ай бұрын
So how would that abstracted function look like exactly? I am genuinely trying to understand. I understand you prefer a nested try catch over the Promise.then, but what is you return type exactly?
@Kriszzzful
@Kriszzzful 2 ай бұрын
@@chris94kennedy a good idea will spread across languages until it gets native implementation. I am not familiar with Go syntax but I found this abstraction readable. Again you are complaining about footguns that already exist, whether you use this approach or not. What exactly would you suggest alternatively?
@chris94kennedy
@chris94kennedy 2 ай бұрын
@@Kriszzzful i wrote a full separate comment on this video that makes my points so i dont feel the need to rewrite it and I'm not talking about syntax, in fact to the contrary ive said that that is the benefit of this approach but leads to issues. I have already made a suggestion so not sure why you're asking for it again, I said learn all the different forms and nuances of async in JS and how to write idiomatic error handling for all the edge cases.
@gearboxworks
@gearboxworks Ай бұрын
Many great ideas that emerge after entrenched dogma appear not to make sense to the majority at first so the majority are very critical when first proposed. But then more and more people start to consider that maybe the new approach is in-fact better than the previously assumed best practice. Over time, the majority go from being critics of the new approach to becoming advocates as the approach becomes mainstream. I watched this happen with classic object-oriented programming vs. containment and delegation, and I expect to see the same happen over the coming years regarding exception handling (try-catch/throw) vs. errors-as-values. #fwiw
@pu239
@pu239 2 ай бұрын
This is how go handles errors by default, very pleasant
@chijiokejoseph7
@chijiokejoseph7 Ай бұрын
Yh it is, just that you return the error second and not first
@darian.rosebrook
@darian.rosebrook Ай бұрын
@@chijiokejoseph7Lol if you’re using JavaScript, probably safe to assume you’re going to get a lot of errors at first
@Takatou__Yogiri
@Takatou__Yogiri 2 ай бұрын
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.
@Kriszzzful
@Kriszzzful 2 ай бұрын
Because some errors inside a try you can handle but others should throw? How would you achieve that in a single try catch?
@hombacom
@hombacom 2 ай бұрын
I see try/catch as few critical unexpected errors and limited scope, known errors should be handled with if, userExists(), result is null etc. It feels wrong to overengineer or add more libraries into the picture when you can simplify instead.
@sfalpha
@sfalpha 2 ай бұрын
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.
@MatTeague
@MatTeague 2 ай бұрын
Thanks for the video and great idea. I have to use a lot of trycatch in my job so this was really interesting. I would really like a video on Effect as it looks cool
@rufio.tf2
@rufio.tf2 2 ай бұрын
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.
@ChristopherBloom
@ChristopherBloom 2 ай бұрын
Hold up. fp-ts is merging with Effect?!
@PeterSahanaya
@PeterSahanaya 27 күн бұрын
yep,i also use Effect/Micro and judt import the things i need like gen, try, tryPromise etc
@nathanl6598
@nathanl6598 Ай бұрын
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.
@jakeave
@jakeave 2 ай бұрын
Thanks for including the types! There's pros and cons to wrapping error handling in every request. I usually end up having a single try catch but the catch calls the application error handler with 10 or so Error types.
@TannerBarcelos
@TannerBarcelos 2 ай бұрын
I fell in love with this approach in Go. So glad this is being adopted into the Typescript ecosystem. It makes so much sense.
@Gakai08
@Gakai08 2 ай бұрын
I like the Rust approach better, just return Result | Error, and then you have to narrow away the Error type to continue using the Result value.
@TannerBarcelos
@TannerBarcelos 2 ай бұрын
@@Gakai08 interesting. I have never used Rust, but I’ve heard this same point from many others. I’ll take a look.
@legends_assemble4938
@legends_assemble4938 2 ай бұрын
​@@Gakai08yes, error handling *feels* better in rust when compared to go. But both the languages embrace errors as values approach, so it's not that much different, just different syntax or pattern.
@wilsonmela6343
@wilsonmela6343 2 ай бұрын
​@@legends_assemble4938 Exactly
@samuraijosh1595
@samuraijosh1595 2 ай бұрын
it goes like this Haskell/Ocaml features -> Rust and Scala adopt them -> more mainstream and normie languages Js, go, pyton adopt them.
@gasparsigma
@gasparsigma 2 ай бұрын
This is useful in an abstraction like your react-query fetcher that can give you the data or handle the error headers/body for you. For everything else try/catch is easier to read
@AlexBojenko
@AlexBojenko 2 ай бұрын
It all started with treating "not exceptional case" as exception. "User does not exist" is a regular workflow. Exception is when you can not connect to the server. From there it all went south. Some weird spaghetti code with promises instead of good old try/catch. Exception is designed to handle the error and exit the function. If you catch it and continue, something is fundamentally wrong.
@ecavero1
@ecavero1 2 ай бұрын
Agreed. No point in continuing if user does not exists, though.
@gearboxworks
@gearboxworks Ай бұрын
Congratulations; you just reinvented the Golang much despised error-handling pattern! (which I happen to appreciate and prefer.) And I mean congratulations sincerely, not sarcastically as try-catch used throughout a codebase is the root of all evil.
@torickjdavis
@torickjdavis 2 ай бұрын
Very similar to the proposal for the safe-assignment operator, which has been modified to try-expressions instead. So we might get some syntax for something like this in the future.
@AbsoluteWoo
@AbsoluteWoo 2 ай бұрын
This video should actually being titled "I don't understand how to use Try/Catch properly"
@maran.ath4
@maran.ath4 2 ай бұрын
This is not an issue with try catch, it's a problem with how you think about architecture, usually no one would store a global user outside their function and set it's value later, you could've literally had the try catch inside the getUser function and return a user from the get user function and do any other error handling in the catch block, when you're writing actual business logic, that repository code will obviously be talking to an external service and "returning" something, not setting a global variable, then some other function in your application logic will call the repository and the getUser will return a user type, if there's any specific error handling try catch will still do the same thing, what you did was to write boilerplate for wrapping then catch
@Suragato
@Suragato 12 күн бұрын
After working in go for a bit, I've come to like the multiple return values with the second value being an optional error. Just check if the error was returned and handle it there. if you return a value regardless of an error, it makes the code even safer.
@refeals
@refeals 2 ай бұрын
Supabase's API works kinda like that. I dont dislike it, but it can get messy with multiple promises with multiple arrays with errors. I guess the best solution depends on your project.
@PepereWorld
@PepereWorld 24 күн бұрын
"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 :)
@kevs3654
@kevs3654 Ай бұрын
I like this approach, already using it :) as golang lover, this approach is the best, less tab more readable
@BorisBarroso
@BorisBarroso 2 ай бұрын
I saw that Theo showed something similar and this comes from go which manages errors this way. You explained this really well and I will copy and adapt your code to my needs. Thanks 🙏
@Tarabass
@Tarabass Ай бұрын
Try catch is a low level pattern and can be used perfectly for catching errors. But, you have to type your errors. In that case you get multiple catches for every error type or an if statement in your catch to check the error type.
@AndresJimenezS
@AndresJimenezS 2 ай бұрын
Effect is awesome, more content about this would be terrific
@juan0338
@juan0338 2 ай бұрын
Cool, but maybe a nice usability addition would be to have a result type (object). Returning an array will inevitably pollute the variable space if you need to use the catch function several times, you will end up with err,err2,err3, etc. You could also declare the results as variables instead of using const, do I don’t know if that is a thing
@bpaintx2
@bpaintx2 2 ай бұрын
Or you could use meaningful variable names. Instead of the incredibly useless err, name it userFetchError.
@dcernach
@dcernach 2 ай бұрын
Basically it is a Result pattern in javascript. Great video by the way! I''ve been using something like this for a while!
@-taz-
@-taz- 2 ай бұрын
Or std::optional in C++ that was from Alexandrescu's 2001 book that became the basis for Result. But I think this is less good than either, and more like Go's error handling, but also worse than that. Interesting, and possibly useful. More like a change of pace than any real benefits.
@killerpixel2k3
@killerpixel2k3 2 ай бұрын
It's the same way the supabase JS SDK handles this issue. They return an object not array but otherwise it's the exact same idea! Great to see how it actually works for anything you want it to, rather than a specific SDK!!!
@fromant65
@fromant65 2 ай бұрын
I've been working in web dev for a few months and I never had a problem with this kind of thing. Though we defined a similar function (tryCatch, which literally tries and catches the callback you pass to it) just to have a more modular code
@dy4914
@dy4914 2 ай бұрын
lad has reinvented golang error handling
@MrMetalGabriel
@MrMetalGabriel 18 күн бұрын
It's a good advice, it's work make it simple... Declaring try/catch block many times in the same function sometimes is boring!
@micknamens8659
@micknamens8659 2 ай бұрын
The motivation in this video is to have specific error handling depending on which of the called functions failed. We do this in the big common catch block by testing the error class (if necessary). Writing log output is already done in the called functions. The only distinction on caller side is whether to retry or whether to continue with a warning vs. rethrow the exception.
@pineappl3pizzzasoju
@pineappl3pizzzasoju 2 ай бұрын
Practically there should be error handling with try/catch in the getUser function to begin with and that would have solved all the problem you mentioned.
@Pluvo2for1
@Pluvo2for1 2 ай бұрын
Thank you Kyle. You're a good guy
@victoreleanya4375
@victoreleanya4375 2 ай бұрын
fantastic, i love this. I learned something new
@Ruchunteur
@Ruchunteur Ай бұрын
isn't it essentially the same as putting a try catch in a separate function instead of writing the logic directly in the current function though ? I mean, I like that it make the original function more readable but you can write the very same logic with your withCatch function being async and using a try/catch/await inside just like in your original function and simply return the same thing you returned in your promise. The point is what your approach didn't really change anything about the usefulness of a try and catch, it's just moved the logic on a separate function but try and catch can be use in that separate function just the same. async function catchError(promise: Promise): Promise { try { return [undefined, await promise] } catch (error) { return [error] } } const [error, user] = await catchError(getUser(1))
@JLuisEstrada
@JLuisEstrada Ай бұрын
This is like one of those infomercials in where clumsy people dont know how to use certain appliance or device, and then comes the savior with a tries to solve a problem that no-one has
@dylan-j-gerrits
@dylan-j-gerrits 2 ай бұрын
It's just a basic abstraction. I always use something similar to wrap my error sensitive block. It makes a lot of sense in middleware to just pass the error to a handler afterward. If not, it is just adding more control flow.
@KostasOreopoulos
@KostasOreopoulos Ай бұрын
This is a long standing debate. Errors as throws or errors as values. If you want to adopt errors as values in javascript, you definitely can. Golang, instead of re-throwing, just bubbles the error, returning it. You can use this at the top level of your throw-rethrow stack, where you will not rethrow the error but handle it. I personally love the errors as values, but everything in Javascript ecosystem is throw based, so it will be a little bit hard. Of course if we get the ?= operator, then things could change.
@akshatmishra8664
@akshatmishra8664 2 ай бұрын
This approach looks similar to how Go handles errors
@蕭宇廷-n4t
@蕭宇廷-n4t 2 ай бұрын
Yeah, I was thinking the same...
@adtc
@adtc 2 ай бұрын
Where do you think he got the idea from? Just another excuse to make a 10 minute video and collect more views.
@Jajoo13
@Jajoo13 2 ай бұрын
@@adtc It doesn't really take a genius to discover this - I've been using this for years already. I do agree - lately I've been seeing more videos about this subject. It seems to be easily milkable so I guess it's because of that. But hey, it's a nice pattern so spreading the word is beneficial.
@zakarylittle6767
@zakarylittle6767 2 ай бұрын
​@@Jajoo13 A nice pattern if you like wasting time and money 😂
@Jajoo13
@Jajoo13 2 ай бұрын
@@zakarylittle6767 ?
@robertholtz
@robertholtz 2 ай бұрын
You really should make it clear that you’re using Typescript here and not vanilla JavaScript. The thumbnail with the JS logo is especially misleading.
@axel_is_gaming
@axel_is_gaming 2 ай бұрын
i was actually expecting JS
@SXsoft99
@SXsoft99 2 ай бұрын
Well yeah but these soy-boys can't write vanilla JS because "oh it's too unsafe" "it's a mess without types" Basically excuses for the inability to deal with stuff
@robertholtz
@robertholtz 2 ай бұрын
@@axel_is_gaming So was I.
@rstuv-0
@rstuv-0 2 ай бұрын
He mostly uses typescript if you are a regular watcher. If you want to use js just remove types its not that difficult or something like that
@robertholtz
@robertholtz 2 ай бұрын
@@rstuv-0 I’ve been watching Kyle for many years, essentially as far back as when he first started on KZbin.
@tejus_sahi
@tejus_sahi 2 ай бұрын
If you use try catch and throw new Error. You can also use console.log(error.message ?? error) in catch block.
@Gabriel-iq6ug
@Gabriel-iq6ug 2 ай бұрын
Your filming approach suggests a thorough understanding of the subject matter.
@ShahzadKhan1234
@ShahzadKhan1234 2 ай бұрын
I just did command + s while watching your code 😁
@ransomecode
@ransomecode 2 ай бұрын
Promise.try will officially will be out soon! It's pretty amazing!
@seanZG
@seanZG 2 ай бұрын
Yes please, would love a tutorial on Effect.
@Surefire99
@Surefire99 2 ай бұрын
I've always wished languages had something like a data type of error or a class of error that had the special property that if you test against it, it always returns false. So a function call would return the normal value, or the error. And you just need to test against the return value to see if it worked. In cases of errors, the object would have properties for the error message, a stack trace, etc.
@matias6798
@matias6798 2 ай бұрын
this video is sooooo bad, literally one of the worst videos I've seen from a "coding" channel in a while but it doesn't surprise me, most of these guys haven't even worked at a proper company to become good devs
@definitive_solutions
@definitive_solutions Ай бұрын
To the ppl saying this would lead to having multiple constants named error, we could return either an Error or a result instead of an array, and verify if result instanceof Error or not
@frisedel
@frisedel 2 ай бұрын
well that's it, I'm adding this to my python code. I need that since I have raise error in multiple places :) thanks!
@dougs-coding-corner
@dougs-coding-corner 2 ай бұрын
I love the deep dive, great job on going through the options and introducing the Effect library at the end! Great to see that error handling is finally getting the attention it deserves. 🚀
@WebDevSimplified
@WebDevSimplified 2 ай бұрын
I just finished taking a glance through your video on the same topic (someone in the comments mentioned your video) and it was well done. I look forward to seeing more content from you in the future as there is a lot JS developers can learn from other languages (like Go).
@dougs-coding-corner
@dougs-coding-corner 2 ай бұрын
@@WebDevSimplified That feedback means a lot coming from you, thank you! ❤️
@woahitsraj
@woahitsraj 2 ай бұрын
We would love a full Effect tutorial. We are thinking of adopting it!
@benyaminyakobi3652
@benyaminyakobi3652 2 ай бұрын
Nice, similar idea of error as a value is a built-in feature in Golang :)
@KlethonioFerreira
@KlethonioFerreira 2 ай бұрын
Doug's Coding Corner posted a video exactly about this 2 days ago.
@jdrab
@jdrab 2 ай бұрын
Congrats you just discovered the go way of handling errors. With CustomErrors it looks like you still want to throw some unknown/unhandled exceptions (errors) like in other languages. the first part is still better than sprinkled try catch blocks all over the codebase, not to mention nested try catch blocks. The go way of handling errors is simply superior. ^^
@seanki
@seanki 2 ай бұрын
If you’re in a react project then react-query is top notch and has this functionality and much more built into hooks
@gweltazlemartret6760
@gweltazlemartret6760 2 ай бұрын
At 1:52 it’s slightly false. You can define a `user` outside try, then affect inside, then exit main path on the catch block, while keeping main path intact. 😊 (Edit: Talked about at 3:02, nice.)
@lilyydotdev
@lilyydotdev Ай бұрын
Personally if the function is one of my own - like a get_user() abstraction of a database call - I like to return errors in the form of an object like `{ error: Error_Enum; data: T }`. To handle exceptions the ORM or any other applicable external function calls might throw I definitely reach for a catch_error() style.
@garyduell3768
@garyduell3768 2 ай бұрын
If I remember correctly, throws or exceptions inside of an async function or context might not actually fire the catch in the calling function.
@adonisengineering5508
@adonisengineering5508 2 ай бұрын
There are other even subtler tricks that a real developer would know about, but typeshit will never let you even get near those edge cases, it is by idiots for idiots, playground guardrails.
@Daniel-zy1ir
@Daniel-zy1ir 2 ай бұрын
@@adonisengineering5508 Let me guess, you code in Vim?
@captainkite
@captainkite 2 ай бұрын
The reason you gave for not using a try catch doesn't make sense at all. While using try catch and logging the error you can print the actual error message by console logging the error plus your custom message. eg catch { console.log('Custom error message' : error)}. Your method is very obscure, I thought you were supposed to simplify the web for us, Kyle.
@akam9919
@akam9919 2 ай бұрын
Forget all the whiners, this great. I hate dealing with the scoping issues that come with try-catch, and I hate that in typescript, the error is basically untyped which, in fairness, it may actually be something you can't actually predict, but I'd rather know if a function call can throw or not, and kinds of errors it can throw.
@RyotsukeHibiki
@RyotsukeHibiki 2 ай бұрын
So re-inventented tanstack query wrapper for async calls?
@BeyondTypeScript
@BeyondTypeScript 2 ай бұрын
Great video! For TypeScript uses, this is a really nice introduction to Effects and Result type. Some languages evolve around the idea of listing side effects (to put it simply), for example, Koka.
@alvincastillo3931
@alvincastillo3931 Ай бұрын
await exist to simplify code, if you move on from try catch sacrificing the await behaviour in favor of then/catch, i dont know but seems to be more boilerplate than the try catch itself afecting the code readability, one simple solution migth be using functions to abstract the logic that you can use inside the try/catch and passing the user as a prop and returning whatever you need
@geek-peek
@geek-peek 2 ай бұрын
There is a problem with catchError function: you don't actually flatten your code, because for each function call you have to add if-else statement. I use another solution: several custom errors extending Error. When I expect an error, I use try/catch and wrap an error inside my own error. Then it is being thrown up to presentation layer and transformed by custom filter, which applies logging and makes a client response based on error type and properties
@abaking9611
@abaking9611 2 ай бұрын
Interesting. Can you explain each part of the function declaration in the catchErrorTyped function. Some of it, I'm not sure I understand.
@chriscordos5622
@chriscordos5622 2 ай бұрын
😆 LoL, 🤦‍♂️ what a funny guy. The main reason try-catch sucks is when it's frivolously used to mitigate foul logical constructs, otherwise it's very necessary for errors that occur beyond your control (mostly external input).
@User948Z7Z-w7n
@User948Z7Z-w7n Ай бұрын
It's a common pattern among data fetching libraries. const {loading,data,error}=useQuery(...
@jsg9575
@jsg9575 2 ай бұрын
Wouldn't do this with enterprise level code
@PraiseYeezus
@PraiseYeezus 2 ай бұрын
enterprise level code bases almost universally wrap fetch and similar operations with their own logic that is even harder to understand than this.
@callanambulancebutnotforme5702
@callanambulancebutnotforme5702 2 ай бұрын
Why not?
@ojikutu
@ojikutu 2 ай бұрын
Why not? Just call it dependency inversion principle...😀
@thejimmylin
@thejimmylin 2 ай бұрын
Every time I see this it reminds me of this funny Go joke: Go always keeps two cups by the bedside. One cup has water, while the other is always empty. Rust asks puzzled: "Why do you always keep two cups here?" Go replies: "Because I need to drink water when I wake up at night." Rust follows up: "But why keep an empty cup?" Go: "What if one day I wake up and don't want to drink water?"
@davidentzat5671
@davidentzat5671 2 ай бұрын
Thanks for the great video. I'll be interested in the video about the Effect library, please
@vsaihruthikreddy7127
@vsaihruthikreddy7127 2 ай бұрын
The video is well-explained, but the approach really depends on the nature of the task. For simpler tasks with fewer sections, using a basic try-catch in each section can be an effective and straightforward solution. However, in extremely complex situations, using catchErrorTyped with await works very well, as it provides more control and clarity in error handling. It’s about using the right tool for the job: just as you’d use a knife to cut vegetables, not a sword, a simple try-catch can be more suitable for simpler needs.
@js9170
@js9170 2 ай бұрын
Effect tutorial would be great! 🎉
@tanishqmanuja
@tanishqmanuja 2 ай бұрын
Allocation of countless extra arrays 😢
@maxbarbul
@maxbarbul 2 ай бұрын
We shouldn’t worry about this as first the code will be transpiled, second, v8 will optimize it. It’s not C. There might not be arrays after all transformation
@tanishqmanuja
@tanishqmanuja 2 ай бұрын
@@maxbarbul I think passing this through tsc will not change anything except stripping the types. Would be happy to see evidence for anything suggesting otherwise.
@maxbarbul
@maxbarbul 2 ай бұрын
@@tanishqmanuja I believe, it might be a bit more than stripping, I’m not saying ts->js would remove array, though . It’s more about first step would change your code, and then v8 would compile and optimize it. and it’s getting more efficient with each new version. If it’s smart enough to recognize similar objects and create internal “classes”, it probably would be able to deal with small arrays in a good way.
@jacobtipp
@jacobtipp 2 ай бұрын
@@maxbarbul No matter what, you're getting JavaScript after transpiling. There is no optimizations from v8 here, those arrays will be allocated as arrays at runtime.
@ShadoFXPerino
@ShadoFXPerino 2 ай бұрын
Nooo don't talk about performance! You're less intelligent than Google engineers therefore you have no authority to talk about performance. The right way is to bow down and pray to our lord and savior v8. Doing so will give you the superpower to write unoptimized code with no scruples because v8 (blessed be thy name) will make it run faster than C.
@dweblinveltz5035
@dweblinveltz5035 2 ай бұрын
JS should just incorporate a new "try/catch" that doesn't create a new scope. They don't even have to break the old version.
@dmltdev
@dmltdev 2 ай бұрын
They seem to be already doing that with a new safe assignment operator `?=`, which is a TC 39 proposal (or other syntax they're currently selecting, like `await try`). It basically does the same, if I got it right.
@seccentral
@seccentral 2 ай бұрын
reminds me of effect error handling (from the functional effect ecosystem of tools, not the react hook) Edit: now that i watched till the end, I can see you mentioned it too 😂
@serg472
@serg472 2 ай бұрын
Right, now you have to deal with nested "if-else" hell: if(error){ if(error2){ if(error3){}}}. This approach comes with a whole set of own drawbacks that you didn't mention. How long have you been using this amazing trick in real projects to understand you want to now ditch all other approaches for good, since last week? If you called the video "another approach to handling errors in js" without sensational clickbait statements then I would say nothing.
@darshanjayadev
@darshanjayadev 2 ай бұрын
Thanks!
@WebDevSimplified
@WebDevSimplified 2 ай бұрын
Thanks for the support!
@mbalaganskiy
@mbalaganskiy 2 ай бұрын
Yet another one - try few nested calls... Welcome back to try/catch
@Marcin2824
@Marcin2824 2 ай бұрын
It is indeed annoying that try/catch in JavaScript does catch compile level errors. However this is easy to avoid by using TypeScript and some linter.
@NaserPapi-x7z
@NaserPapi-x7z 2 ай бұрын
It would be greatly appreciated if you could create a tutorial about the Effect library. It seems amazing for special scenarios.
@justsomeguy8385
@justsomeguy8385 2 ай бұрын
Sure it's a better experience, but the language doesn't force it so almost no one will do this. New projects using this will eventually get developers who ruin the pattern, and now you're left with some places where errors are handled like this, some places with try/catch, and places where error catching doesn't happen at all This needs to be part of a library to be useful(I agree, effect is too bloated if you just want this), and there needs to be strict linter rules to prevent people from doing it any other way.
@ragtop63
@ragtop63 2 ай бұрын
I come from C#. When I was learning C# I quickly exceeded the practical usability of try/catch. I typically end up building a lightweight error handling class that can be used globally. Needless to say, I quickly ran into the same issue with TypeScript. Unless I’m dealing with an extremely simple scenario, I really don’t ever use try/catch.
@BRBS360
@BRBS360 2 ай бұрын
Interestingly enough, I've read that C#/.NET is getting some Result (Optional) Type on a language level. Not sure if I like this or just prefer to just keep my functions small so try/catch never overextends its reach.
@stephenb_dev
@stephenb_dev 2 ай бұрын
Yeah No. This trend of ditching try-catch is funny. I remember the good old days when errors by value was big no no. What happened to keeping business logic separate from error management ? The main reason I don't like Go. No try-catch.
@Kevin-fl4rn
@Kevin-fl4rn 2 ай бұрын
Couldn't you just extract the try catch into a function and have it return your data as well as any error handling. Then you can just call the function and have your data be at the top level like you wanted. Seems like itd be a lot easier than making these large catch error to handle all edge cases
@rodrigopim7693
@rodrigopim7693 2 ай бұрын
You can have several catches in a try code block and throw your exceptions by treating each case separately.
@anonlegion9096
@anonlegion9096 2 ай бұрын
Why does it really sound like you're talking about the result pattern? I heard Js just got a recent update that facilitates this pattern
@randymartin9040
@randymartin9040 2 ай бұрын
I'm a bit confused, in your original example where you log the error, couldn't you have just logged the error.message in the console log there? It seems like you've just added redundancy to the function, no? No offense I just don't understand, thank you.
@double-agent-ly
@double-agent-ly 2 ай бұрын
The first argument should be a function that returns a promise, not a promise by itself.
@helidrones
@helidrones 2 ай бұрын
What do you think about returning [null, data] or [error, null] ?
@Jajoo13
@Jajoo13 2 ай бұрын
Error first is better because it forces you to acknowledge it. However, don't return null - use undefined.
@kkingbd
@kkingbd 2 ай бұрын
catch(error) there for a reason. You can get an idea about the error once you read the error.
This Folder Structure Makes Me 100% More Productive
24:36
Web Dev Simplified
Рет қаралды 113 М.
@property Is One Of The Coolest New CSS Features
10:41
Web Dev Simplified
Рет қаралды 45 М.
Support each other🤝
00:31
ISSEI / いっせい
Рет қаралды 81 МЛН
1% vs 100% #beatbox #tiktok
01:10
BeatboxJCOP
Рет қаралды 67 МЛН
Therapy Progress Notes, Client progress, Therapy documentation, Mental health records
2:44
Therapist Resources: Spreadsheets & Workbooks Hub
Рет қаралды 3,7 М.
Only The Best Developers Understand How This Works
18:32
Web Dev Simplified
Рет қаралды 116 М.
The Actual Dumbest Thing About Try/Catch
11:47
Theo - t3․gg
Рет қаралды 48 М.
Learn TypeScript Generics In 13 Minutes
12:52
Web Dev Simplified
Рет қаралды 294 М.
Product Engineering with Cursor AI: Let's build a Next.js app!
16:23
Web Developers Are Disconnected
21:36
ThePrimeTime
Рет қаралды 221 М.
The Honey Scam: Explained
10:53
Marques Brownlee
Рет қаралды 3,8 МЛН
Reacting to Controversial Opinions of Software Engineers
9:18
Fireship
Рет қаралды 2,1 МЛН
This VS Code theme is threatening people?
14:26
Theo - t3․gg
Рет қаралды 133 М.