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

preview_player
Показать описание
Handling JavaScript errors doesn't get enough attention. When you start working on bigger and more complex applications, this becomes more and more important!

**Newsletter**

**DISCORD**

**QUESTIONS ABOUT MY SETUP**
Рекомендации по теме
Комментарии
Автор

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 }.

marcusradell
Автор

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 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`.

ruanmoreiraofc
Автор

Your ReturnValue<T> is also called a Result<T> object in other languages. It's a very simple but powerful structure.

soverain
Автор

Hi james, why you didn't use safeParse its better than using only parse, in this case you will have success and data/error

gamingwolf
Автор

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

rembautimes
Автор

Which color theme is this? I checked your uses pagesbut it's not the same theme here?

PieterMoeyersons
Автор

Great video! Try/catch is a nightmare to deal with.... my if err != nil { is looking so good right now 😂

coffeeintocode
Автор

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

darawan_omar
Автор

1:56 C# does not have checked exceptions

rodjenihm
Автор

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.

xpamamadeus
Автор

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.

bycsflu
Автор

The other case when typing HOCs, use something like this:

```ts
function wrapper<T extends Array<unknown>, R>(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!

ruanmoreiraofc
Автор

kind of few people talk about it, thank you

naranyala_dev
Автор

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

buddy.abc
Автор

TS does not have any `throws` operator, but JSDOC has /** @throws */
It might be helpful at least from intellisense visible doc part

georgipetkov
Автор

you try to rework monad "Either" or "Result"
just use it :)

snatvb
Автор

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.

dan
Автор

1:56 actually, C# doesn’t have the `throws` annotation. I wish it had. Only Java has that annotation.

maacpiash
Автор

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 i'd check if result.length > 0,

troooooper
Автор

@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.

VinnyXL