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.
@moonwhisperer48042 ай бұрын
I don’t buy it… you can just put try catch on separate sections … just keep it simple
@caribouroadfarm2 ай бұрын
Not only that you can have multiple catch clauses for a try clause.
@genechristiansomoza49312 ай бұрын
Usually the controller is the best place to put try catch
@Kriszzzful2 ай бұрын
@@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?
@vagkalosynakis2 ай бұрын
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
@caribouroadfarm2 ай бұрын
@@Kriszzzful I don't know if you can post links here, but those things called Conditional catch clauses just google it
@clevermissfox2 ай бұрын
We’ve come full circle; ditching try/catch for .then().catch() 😆
@moligun832 ай бұрын
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.
@dio563012 ай бұрын
yeah, was thinking the same (that it could be rewritten to async try/catch) ... so what am I missing here?
@gohancomfejao2 ай бұрын
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.
@thescientisthorse2 ай бұрын
I get "callback hell" vibe
@WhiteVanyo2 ай бұрын
@@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.
@johnlagnese70762 ай бұрын
"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
@johnridout65402 ай бұрын
It's actually a very simple function. Here's a pure JavaScript version. const catchError = promise => promise .then(data => [undefined, data]) .catch(error => [error])
@josephvictory95362 ай бұрын
@@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.
@chris94kennedy2 ай бұрын
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.
@amineabdz2 ай бұрын
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
@chris94kennedy2 ай бұрын
@@amineabdz i think you're missing what im putting down
@jsvrs2 ай бұрын
it's hard to read. try adding some line spaces.
@chris94kennedy2 ай бұрын
@@jsvrs fair enough, have done so
@justsomeguy83852 ай бұрын
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.
@risitas58742 ай бұрын
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"
@ojikutu2 ай бұрын
We've also managed to escape the variable scoping of try-catch
@Blafasel32 ай бұрын
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.
@risitas58742 ай бұрын
@@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Ай бұрын
@@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.
@notoavinarazafilalao74152 ай бұрын
we don't talk much about Effect, this lib is impressive
@eprd3132 ай бұрын
What do you use it for mostly if I may ask?
@notoavinarazafilalao74152 ай бұрын
@@eprd313 Honestly, I'm not fully using it in my codebase yet, but you can watch Lucas Barake's videos with some cool examples
@PeterSahanaya13 күн бұрын
@@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
@pomprocks2 ай бұрын
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.
@RmonikMusic2 ай бұрын
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.
@ericmackrodt94412 ай бұрын
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.
@krtirtho2 ай бұрын
Once a wise man said, "Don't bring one language's convention in another language"
@Nguyen-c7z2 ай бұрын
Cause it's honestly stupid. No proper developer write try catch like that anyway. This is junior example.
@chris94kennedy2 ай бұрын
it is *not* exactly what golang does.
@ericmackrodt94412 ай бұрын
@@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.
@chris94kennedy2 ай бұрын
@@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.
@alii43342 ай бұрын
I prefer "withCatch" as name to tell it is a wrapper
@dmltdev2 ай бұрын
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); } }
@dmltdev2 ай бұрын
Misunderstood at first. Disregard pls.
@MerthanMerter2 ай бұрын
i prefer $catch
@4sxS307cAW2 ай бұрын
i prefer create a catch factory. we are not the same.
@Gabriel-iq6ug2 ай бұрын
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Ай бұрын
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...
@EricSundquistKC2 ай бұрын
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.
@Jajoo132 ай бұрын
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.
@Smoljames2 ай бұрын
An interesting approach but perhaps this is fixing smth that isn't broken?
@Jajoo132 ай бұрын
This is no fix - it's an improvement over standard try/catch.
@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
@samjohnston882 ай бұрын
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
@chris94kennedy2 ай бұрын
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.
@Kriszzzful2 ай бұрын
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?
@Kriszzzful2 ай бұрын
@@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?
@chris94kennedy2 ай бұрын
@@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Ай бұрын
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
@pu2392 ай бұрын
This is how go handles errors by default, very pleasant
@chijiokejoseph7Ай бұрын
Yh it is, just that you return the error second and not first
@darian.rosebrookАй бұрын
@@chijiokejoseph7Lol if you’re using JavaScript, probably safe to assume you’re going to get a lot of errors at first
@Takatou__Yogiri2 ай бұрын
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.
@Kriszzzful2 ай бұрын
Because some errors inside a try you can handle but others should throw? How would you achieve that in a single try catch?
@hombacom2 ай бұрын
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.
@sfalpha2 ай бұрын
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.
@MatTeague2 ай бұрын
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.tf22 ай бұрын
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.
@ChristopherBloom2 ай бұрын
Hold up. fp-ts is merging with Effect?!
@PeterSahanaya27 күн бұрын
yep,i also use Effect/Micro and judt import the things i need like gen, try, tryPromise etc
@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.
@jakeave2 ай бұрын
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.
@TannerBarcelos2 ай бұрын
I fell in love with this approach in Go. So glad this is being adopted into the Typescript ecosystem. It makes so much sense.
@Gakai082 ай бұрын
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.
@TannerBarcelos2 ай бұрын
@@Gakai08 interesting. I have never used Rust, but I’ve heard this same point from many others. I’ll take a look.
@legends_assemble49382 ай бұрын
@@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.
@wilsonmela63432 ай бұрын
@@legends_assemble4938 Exactly
@samuraijosh15952 ай бұрын
it goes like this Haskell/Ocaml features -> Rust and Scala adopt them -> more mainstream and normie languages Js, go, pyton adopt them.
@gasparsigma2 ай бұрын
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
@AlexBojenko2 ай бұрын
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.
@ecavero12 ай бұрын
Agreed. No point in continuing if user does not exists, though.
@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.
@torickjdavis2 ай бұрын
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.
@AbsoluteWoo2 ай бұрын
This video should actually being titled "I don't understand how to use Try/Catch properly"
@maran.ath42 ай бұрын
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
@Suragato12 күн бұрын
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.
@refeals2 ай бұрын
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.
@PepereWorld24 күн бұрын
"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Ай бұрын
I like this approach, already using it :) as golang lover, this approach is the best, less tab more readable
@BorisBarroso2 ай бұрын
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Ай бұрын
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.
@AndresJimenezS2 ай бұрын
Effect is awesome, more content about this would be terrific
@juan03382 ай бұрын
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
@bpaintx22 ай бұрын
Or you could use meaningful variable names. Instead of the incredibly useless err, name it userFetchError.
@dcernach2 ай бұрын
Basically it is a Result pattern in javascript. Great video by the way! I''ve been using something like this for a while!
@-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.
@killerpixel2k32 ай бұрын
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!!!
@fromant652 ай бұрын
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
@dy49142 ай бұрын
lad has reinvented golang error handling
@MrMetalGabriel18 күн бұрын
It's a good advice, it's work make it simple... Declaring try/catch block many times in the same function sometimes is boring!
@micknamens86592 ай бұрын
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.
@pineappl3pizzzasoju2 ай бұрын
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.
@Pluvo2for12 ай бұрын
Thank you Kyle. You're a good guy
@victoreleanya43752 ай бұрын
fantastic, i love this. I learned something new
@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Ай бұрын
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-gerrits2 ай бұрын
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Ай бұрын
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.
@akshatmishra86642 ай бұрын
This approach looks similar to how Go handles errors
@蕭宇廷-n4t2 ай бұрын
Yeah, I was thinking the same...
@adtc2 ай бұрын
Where do you think he got the idea from? Just another excuse to make a 10 minute video and collect more views.
@Jajoo132 ай бұрын
@@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.
@zakarylittle67672 ай бұрын
@@Jajoo13 A nice pattern if you like wasting time and money 😂
@Jajoo132 ай бұрын
@@zakarylittle6767 ?
@robertholtz2 ай бұрын
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_gaming2 ай бұрын
i was actually expecting JS
@SXsoft992 ай бұрын
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
@robertholtz2 ай бұрын
@@axel_is_gaming So was I.
@rstuv-02 ай бұрын
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
@robertholtz2 ай бұрын
@@rstuv-0 I’ve been watching Kyle for many years, essentially as far back as when he first started on KZbin.
@tejus_sahi2 ай бұрын
If you use try catch and throw new Error. You can also use console.log(error.message ?? error) in catch block.
@Gabriel-iq6ug2 ай бұрын
Your filming approach suggests a thorough understanding of the subject matter.
@ShahzadKhan12342 ай бұрын
I just did command + s while watching your code 😁
@ransomecode2 ай бұрын
Promise.try will officially will be out soon! It's pretty amazing!
@seanZG2 ай бұрын
Yes please, would love a tutorial on Effect.
@Surefire992 ай бұрын
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.
@matias67982 ай бұрын
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Ай бұрын
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
@frisedel2 ай бұрын
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-corner2 ай бұрын
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. 🚀
@WebDevSimplified2 ай бұрын
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-corner2 ай бұрын
@@WebDevSimplified That feedback means a lot coming from you, thank you! ❤️
@woahitsraj2 ай бұрын
We would love a full Effect tutorial. We are thinking of adopting it!
@benyaminyakobi36522 ай бұрын
Nice, similar idea of error as a value is a built-in feature in Golang :)
@KlethonioFerreira2 ай бұрын
Doug's Coding Corner posted a video exactly about this 2 days ago.
@jdrab2 ай бұрын
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. ^^
@seanki2 ай бұрын
If you’re in a react project then react-query is top notch and has this functionality and much more built into hooks
@gweltazlemartret67602 ай бұрын
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Ай бұрын
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.
@garyduell37682 ай бұрын
If I remember correctly, throws or exceptions inside of an async function or context might not actually fire the catch in the calling function.
@adonisengineering55082 ай бұрын
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-zy1ir2 ай бұрын
@@adonisengineering5508 Let me guess, you code in Vim?
@captainkite2 ай бұрын
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.
@akam99192 ай бұрын
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.
@RyotsukeHibiki2 ай бұрын
So re-inventented tanstack query wrapper for async calls?
@BeyondTypeScript2 ай бұрын
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Ай бұрын
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-peek2 ай бұрын
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
@abaking96112 ай бұрын
Interesting. Can you explain each part of the function declaration in the catchErrorTyped function. Some of it, I'm not sure I understand.
@chriscordos56222 ай бұрын
😆 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Ай бұрын
It's a common pattern among data fetching libraries. const {loading,data,error}=useQuery(...
@jsg95752 ай бұрын
Wouldn't do this with enterprise level code
@PraiseYeezus2 ай бұрын
enterprise level code bases almost universally wrap fetch and similar operations with their own logic that is even harder to understand than this.
@callanambulancebutnotforme57022 ай бұрын
Why not?
@ojikutu2 ай бұрын
Why not? Just call it dependency inversion principle...😀
@thejimmylin2 ай бұрын
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?"
@davidentzat56712 ай бұрын
Thanks for the great video. I'll be interested in the video about the Effect library, please
@vsaihruthikreddy71272 ай бұрын
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.
@js91702 ай бұрын
Effect tutorial would be great! 🎉
@tanishqmanuja2 ай бұрын
Allocation of countless extra arrays 😢
@maxbarbul2 ай бұрын
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
@tanishqmanuja2 ай бұрын
@@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.
@maxbarbul2 ай бұрын
@@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.
@jacobtipp2 ай бұрын
@@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.
@ShadoFXPerino2 ай бұрын
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.
@dweblinveltz50352 ай бұрын
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.
@dmltdev2 ай бұрын
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.
@seccentral2 ай бұрын
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 😂
@serg4722 ай бұрын
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.
@darshanjayadev2 ай бұрын
Thanks!
@WebDevSimplified2 ай бұрын
Thanks for the support!
@mbalaganskiy2 ай бұрын
Yet another one - try few nested calls... Welcome back to try/catch
@Marcin28242 ай бұрын
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-x7z2 ай бұрын
It would be greatly appreciated if you could create a tutorial about the Effect library. It seems amazing for special scenarios.
@justsomeguy83852 ай бұрын
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.
@ragtop632 ай бұрын
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.
@BRBS3602 ай бұрын
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_dev2 ай бұрын
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-fl4rn2 ай бұрын
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
@rodrigopim76932 ай бұрын
You can have several catches in a try code block and throw your exceptions by treating each case separately.
@anonlegion90962 ай бұрын
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
@randymartin90402 ай бұрын
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-ly2 ай бұрын
The first argument should be a function that returns a promise, not a promise by itself.
@helidrones2 ай бұрын
What do you think about returning [null, data] or [error, null] ?
@Jajoo132 ай бұрын
Error first is better because it forces you to acknowledge it. However, don't return null - use undefined.
@kkingbd2 ай бұрын
catch(error) there for a reason. You can get an idea about the error once you read the error.