JavaScript Error Handling: 5 Things You Aren’t Thinking About!

  Рет қаралды 15,006

James Q Quick

James Q Quick

Күн бұрын

Handling JavaScript errors doesn't get enough attention. When you start working on bigger and more complex applications, this becomes more and more important!
Check out Sentry for error tracking and alerting - sentry.io/
*Newsletter*
Newsletter 🗞 - www.jamesqquick.com/newsletter
*DISCORD*
Join the Learn Build Teach Discord Server 💬 - / discord
Follow me on Twitter 🐦 - / jamesqquick
Check out the Podcast - compressed.fm/
Courses - jamesqquick.com/courses
*QUESTIONS ABOUT MY SETUP*
Check out my Uses page for my VS Code setup, what recording equipment I use, etc. www.jamesqquick.com/uses

Пікірлер: 62
@marcusradell7544
@marcusradell7544 2 ай бұрын
Error handling in TS made me learn Rust. And I do like to emulate the Result type. It's basically what you do, but with a tagged field { ok: true } | { ok: false }.
@AntonGorbachevDev
@AntonGorbachevDev 2 ай бұрын
We can use same way in typescript, by using oxide.ts/fp-ts/effect.ts)
@user-of6ls2ng5l
@user-of6ls2ng5l Ай бұрын
Show me an example)
@ruanmoreiraofc
@ruanmoreiraofc 2 ай бұрын
TS does not have any `throws` operator, but there is one called `asserts`. I think this is what you are looking for, here is a use case: ```ts function assertIsNumber(possibleNumber: unknown): asserts possibleNumber is number { const isNumber = typeof possibleNumber === 'number'; if (!isNumber) throw new Error(); } let input: string | number = 'aaa'; // input = 3.1415; assertIsNumber(input); input.toString(); ``` The code as it is now, will throw an error, because `input` is the type `never` in the last line. But, when the `input` reassignment is uncommented it will pass normally because the function `assertIsNumber` will stop changing the type of `input` to `never`.
@user-by8cs2fl7u
@user-by8cs2fl7u 2 ай бұрын
My fist comment is: instead of this functional approach, you can simply implement a decorator as a wrapper. Much cleaner and more understandable. Second: I would not recommend to return the error message because that makes the error a part of the domain data and it is not a good practice. Always better to use exceptions and implement your our exception handler(s) on different abstraction levels.
@keithjohnson6510
@keithjohnson6510 2 ай бұрын
Totally agree, unfortunately good as they are, this video is just adding confusion. try catch throw, once understood correctly means error handling is really the easiest part of coding. Rust's error handling is a step backwards, and people trying to use the same construct in JS land is bonkers. It's nothing to do with functional coding either before anyone pull that nugget out.
@alejandroechavarria539
@alejandroechavarria539 2 ай бұрын
Thanks for your comment, so useful
@Anbaraen
@Anbaraen Ай бұрын
Do you have any recs for the "right" way to do testing in JS?
@soverain
@soverain 2 ай бұрын
Your ReturnValue is also called a Result object in other languages. It's a very simple but powerful structure.
@JamesQQuick
@JamesQQuick 2 ай бұрын
Love it. What languages do you see that in?
@soverain
@soverain 2 ай бұрын
@@JamesQQuick I'm using it in C#. Saw it in Java. It's even built in Rust. It's a well known construct in functional programming.
@nage7447
@nage7447 2 ай бұрын
@@soverain in C# and Java it is hand made, probably better to refer to F# where Option and Result is build in structures
@soverain
@soverain 2 ай бұрын
@@nage7447 sure, but most implementations are good.
@ruanmoreiraofc
@ruanmoreiraofc 2 ай бұрын
The other case when typing HOCs, use something like this: ```ts function wrapper(fn: (...args: T) => R) { return fn; } const fn = (a: number, b: number) => a * b; const result = wrapper(fn)(1, 2); ``` `result` will be the correct returning type and when you forgot any param, TS will warn you!
@nage7447
@nage7447 2 ай бұрын
yea, but, you want to execute a function inside another function, so you need to pass arguments inside function wrapper(fn: (...args: T) => R, ...args: T) { try { fn(...args); } catch { ... } } const fn = (a: number, b: number) => a * b; const result = wrapper(fn, 1, 2);
@coffeeintocode
@coffeeintocode 2 ай бұрын
Great video! Try/catch is a nightmare to deal with.... my if err != nil { is looking so good right now 😂
@IvanRandomDude
@IvanRandomDude 2 ай бұрын
Indeed. When people say they hate error handling in Go what they actually mean is that they hate error handling period! They simply don't handle errors at all. The amount of code I have seen where people just invoke billion functions that can throw trillion errors without any try catch is insane. I like to call it "happy path" coding which basically it is, you just code the scenario where everything works 100% of the time.
@JamesQQuick
@JamesQQuick 2 ай бұрын
haha error handling gets really complicated really quickly
@keithjohnson6510
@keithjohnson6510 2 ай бұрын
It's just miss-understood. I think once grasped is way easier than ReturnValue.. Basically if your using try catch a lot in your code, chances are you using it wrong..
@ErnestOak
@ErnestOak 2 ай бұрын
Why I do not use async await
@natescode
@natescode 2 ай бұрын
Please GOd no 😭
@gamingwolf3385
@gamingwolf3385 2 ай бұрын
Hi james , why you didn't use safeParse its better than using only parse , in this case you will have success and data/error
@rembautimes8808
@rembautimes8808 2 ай бұрын
Good video and also good for sentry to have sponsored this video. I think a longer sponsored video explaining the common errors encountered in JS and developing a best practice guide will be great. Also can showcase how sentry should be integrated into an enterprise application. For context, I work in tech risk management in a financial institution
@valenciawalker6498
@valenciawalker6498 Ай бұрын
Thank you!
@PieterMoeyersons
@PieterMoeyersons 2 ай бұрын
Which color theme is this? I checked your uses pagesbut it's not the same theme here?
@xpamamadeus
@xpamamadeus 2 ай бұрын
preferences.. user errors that are actually validation errors have 2 paths,one happy where no error and other that returns predefined message what kind of data they must enter to avoid error really simple. other errors like in backend should not exist and easiest its to just avoid js in backends.
@snatvb
@snatvb 2 ай бұрын
you try to rework monad "Either" or "Result" just use it :)
@KDEDflyr55
@KDEDflyr55 2 ай бұрын
purify-ts. It’s fantastic if you want monads without having to go deep with fp-ts
@snatvb
@snatvb 2 ай бұрын
@@KDEDflyr55 Thanks, I'll keep that in mind. Actually fp-ts has them serializable, which I like, because structure is just data.
@RockTheCage55
@RockTheCage55 2 ай бұрын
excellent....thanks
@JamesQQuick
@JamesQQuick 2 ай бұрын
Thanks for watching!
@naranyala_dev
@naranyala_dev 2 ай бұрын
kind of few people talk about it, thank you
@rodjenihm
@rodjenihm 2 ай бұрын
1:56 C# does not have checked exceptions
@JamesQQuick
@JamesQQuick 2 ай бұрын
Ah good catch. Someone else called that out as well. Thanks for clarifying!
@darawan_omar
@darawan_omar 2 ай бұрын
I use auth js version 5 in when user loginned and visit a page that not access into it how we can logout the user by using the function signOut for clearing session in middleware in auth js
@buddy.abc123
@buddy.abc123 2 ай бұрын
1:56 C# does not do that as a you've already been corrected. But...can I suggest you look at GO? I'm a day-to-day C# dev btw
@dan110024
@dan110024 Ай бұрын
I was just thinking your opening line when searching for a video! Heaps of videos talking about try/catch blocks but nothing talking about strategy.
@troooooper100
@troooooper100 17 күн бұрын
What about returning the Error? then doing if (result instanceof Error) i feel throwing error is useless, 9/10 times you have to propagate the error upstream, so catching the error and doing the same thing which was gonna happen automatically is kinda pointless. and as you said in js ecosystem usually you either get a response or {err} or [data, err] or fn(data, err) nobody is expecting whole program to crash because of one function call ... for example if i do parseStr(.....), i'd check if result.length > 0 ,
@VinnyXL420
@VinnyXL420 2 ай бұрын
@1:57 You would need to use JSDoc and annotate whatever it is you want to annotate, in case of functions or callables, you can add the @throws decorator and add some text. Like: /** * Parses the given string or throws an error * @throws Throws an error on failure */ function parseString(str: string): string { } Then when hovering over the function call, you should see all these details. And in VSC if you also hold ctrl while hovering over it you get more details. Even though typescript infers all the input and output types automatically, it is always good practice to add return types, so that in the future you dont return something unexpected when refactoring your shit code, because you WILL refactor it at some point. Funny enough, in JS we can return Errors as values, and then just check for `instanceof Error`, if it is... well, its an error and you can decide to throw it or not, instead of it being thrown in the API and you catching the throw. This reduces the need for the generic Result type as you only need to check for an instance of error. This is less acceptable in JS, since most API's just throw the damn errors anyway, so most developers are used to this Java paradigm of catching errors, instead of passing errors as values.
@keithjohnson6510
@keithjohnson6510 2 ай бұрын
-> since most API's just throw the damn errors Correct, and that's how it should be if the error is an exception.
@georgipetkov9080
@georgipetkov9080 2 ай бұрын
TS does not have any `throws` operator, but JSDOC has /** @throws */ It might be helpful at least from intellisense visible doc part
@damonholden
@damonholden 2 ай бұрын
Disappointed `error.cause` wasn't mentioned for wrapping errors in JS. Imo we should all be using that to construct more readable error objects. Also this idea of returning objects with properties for errors is silly to me when we already have try catch. Why bring in this construct that has to be adopted on top of the try catch syntax when it achieves the same thing and adds added overhead to the GC by making needless objects everywhere. The only way I can see this practice being viable is if you want to throw an error along with some data that is constructed depending on how a function errors, in which case, it is viable to throw an object with an error object and the data as 2 separate properties. Also, never liked the idea of creating an abstraction to the error handling process. This always adds needless complexity and bypasses core functionality of JavaScript errors in some way. Just write `try catch` blocks people, your just gonna shoot yourself in the foot adopting these weird practices. And please please please wrap your errors, you'll thank yourself in the long run.
@maacpiash
@maacpiash 2 ай бұрын
1:56 actually, C# doesn’t have the `throws` annotation. I wish it had. Only Java has that annotation.
@ChristianKolbow
@ChristianKolbow 2 ай бұрын
12:09 It should look like this: Line34: const result = withErrorHandling(parseStringInput(10)) The (10) belongs in the "withErrorHandling" function. Then it should work. And of course a great video. Thank you
@JamesQQuick
@JamesQQuick 2 ай бұрын
Ah good catch! Thanks!!
@jonathangamble
@jonathangamble 2 ай бұрын
Still haven't tried Valibot?
@vivekkaushik9508
@vivekkaushik9508 2 ай бұрын
These thumbnails are getting crazy 😂. Nice vid tho.
@JamesQQuick
@JamesQQuick 2 ай бұрын
haha yeah. Any suggfestions?
@victorhenriquecollasanta4740
@victorhenriquecollasanta4740 2 ай бұрын
Error handling is time consuming and make the code ugly, I wish that we had a cleaner way to do it
@keithjohnson6510
@keithjohnson6510 2 ай бұрын
What would be great, would be a way to code something, but when something didn't happen as expected some sort of exception was thrown that could be caught. You could then target some place to handle these errors, if these errors could just propagate upwards too, that would be fantastic. Oh, eh, I think I've just described try / catch / throw.. :) Joking aside, honestly I've code bases with thousands of units and error handling is the least of my worries.
@shakapaker
@shakapaker 2 ай бұрын
why just not to throw an err
@JamesQQuick
@JamesQQuick 2 ай бұрын
In which scenario specifically?
@shakapaker
@shakapaker 2 ай бұрын
@@JamesQQuick instead of object with error
@victorhenriquecollasanta4740
@victorhenriquecollasanta4740 2 ай бұрын
If you are working with next js ,if the function that throw an error is running on the server, it will not share the error infos with the client. The only way you can share the error message is by passing the error infos in the error object (this happened to me) and then log it on the client for the user
2 ай бұрын
damn i loved this channel. shame that I have to unsub. hate when serious guys go for lame clickbait videoicon with stupid face expression. anyway, thanks James, and bye.
@zettxxx
@zettxxx 2 ай бұрын
why do we need to create api over another api ? just learn first one and stop creating api wrapper of another api wrapper of another api wrapper ....
@JamesQQuick
@JamesQQuick 2 ай бұрын
What are you talking about specifically?
@zettxxx
@zettxxx 2 ай бұрын
@@JamesQQuick im talking about javascript error handling api.
Tips and Tricks for Debugging JavaScript
13:03
James Q Quick
Рет қаралды 403 М.
10 JavaScript Interview Questions You HAVE TO KNOW
13:41
James Q Quick
Рет қаралды 39 М.
КАКОЙ ВАШ ЛЮБИМЫЙ ЦВЕТ?😍 #game #shorts
00:17
Cat story: from hate to love! 😻 #cat #cute #kitten
00:40
Stocat
Рет қаралды 8 МЛН
1 класс vs 11 класс (неаккуратность)
01:00
БЕРТ
Рет қаралды 2,1 МЛН
SHE WANTED CHIPS, BUT SHE GOT CARROTS 🤣🥕
00:19
OKUNJATA
Рет қаралды 14 МЛН
5 Async + Await Error Handling Strategies
18:11
Wes Bos
Рет қаралды 19 М.
err != nil Is GOOD? (And Why)
7:19
ThePrimeTime
Рет қаралды 85 М.
How To Handle Errors in Node.js and TypeScript
37:23
Mark Maksi
Рет қаралды 3,9 М.
5 Signs of an Inexperienced Self-Taught Developer (and how to fix)
8:40
Learn TypeScript Generics In 13 Minutes
12:52
Web Dev Simplified
Рет қаралды 206 М.
STOP Using JavaScript For These 5 Things!
8:05
James Q Quick
Рет қаралды 17 М.
Finally Fix Your Issues With JS/React Memory Management 😤
20:13
Jack Herrington
Рет қаралды 78 М.
Code Review with a Jr JavaScript Developer - Here's What I Found!
10:03
Top 10 Javascript One Liners YOU MUST KNOW!
14:16
developedbyed
Рет қаралды 190 М.
КАКОЙ ВАШ ЛЮБИМЫЙ ЦВЕТ?😍 #game #shorts
00:17