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 }.
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`.
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.
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.
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!
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);
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.
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..
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
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.
@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.
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
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.
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 ,
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
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.
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
7 місяців тому
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.
Your ReturnValue is also called a Result object in other languages. It's a very simple but powerful structure.
Love it. What languages do you see that in?
@@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.
@@soverain in C# and Java it is hand made, probably better to refer to F# where Option and Result is build in structures
@@nage7447 sure, but most implementations are good.
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 }.
We can use same way in typescript, by using oxide.ts/fp-ts/effect.ts)
Show me an example)
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`.
No, that is completly different.
"Throws" would tell user of the function that it throws some error, it doesnt throw anything itself.
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.
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.
Thanks for your comment, so useful
Do you have any recs for the "right" way to do testing in JS?
@@keithjohnson6510 would you please recommend a video/tutorial to learn the error handling an easy/right way?
would you please recommend a video/tutorial to learn the error handling an easy/right way?
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!
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);
Great video! Try/catch is a nightmare to deal with.... my if err != nil { is looking so good right now 😂
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.
haha error handling gets really complicated really quickly
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..
Why I do not use async await
Please GOd no 😭
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
Hi james , why you didn't use safeParse its better than using only parse , in this case you will have success and data/error
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.
you try to rework monad "Either" or "Result"
just use it :)
purify-ts. It’s fantastic if you want monads without having to go deep with fp-ts
@@KDEDflyr55 Thanks, I'll keep that in mind.
Actually fp-ts has them serializable, which I like, because structure is just data.
@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.
-> since most API's just throw the damn errors Correct, and that's how it should be if the error is an exception.
TS does not have any `throws` operator, but JSDOC has /** @throws */
It might be helpful at least from intellisense visible doc part
Which color theme is this? I checked your uses pagesbut it's not the same theme here?
kind of few people talk about it, thank you
1:56 C# does not have checked exceptions
Ah good catch. Someone else called that out as well. Thanks for clarifying!
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
Ah good catch! Thanks!!
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.
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
Thank you!
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.
1:56 actually, C# doesn’t have the `throws` annotation. I wish it had. Only Java has that annotation.
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 ,
excellent....thanks
Thanks for watching!
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
These thumbnails are getting crazy 😂. Nice vid tho.
haha yeah. Any suggfestions?
Still haven't tried Valibot?
tbh, i don't like this way. I'd prefer:
const [ data, error ] = someFunction();
and handle the error inside the function.
Error handling is time consuming and make the code ugly, I wish that we had a cleaner way to do it
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.
why just not to throw an err
In which scenario specifically?
@@JamesQQuick instead of object with error
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
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.