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

Поділитися
Вставка
  • Опубліковано 9 лис 2024

КОМЕНТАРІ • 66

  • @soverain
    @soverain 7 місяців тому +5

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

    • @JamesQQuick
      @JamesQQuick  7 місяців тому +1

      Love it. What languages do you see that in?

    • @soverain
      @soverain 7 місяців тому +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 7 місяців тому

      @@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 7 місяців тому

      @@nage7447 sure, but most implementations are good.

  • @marcusradell7544
    @marcusradell7544 7 місяців тому +12

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

  • @ruanmoreiraofc
    @ruanmoreiraofc 7 місяців тому +5

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

    • @symix.
      @symix. Місяць тому

      No, that is completly different.
      "Throws" would tell user of the function that it throws some error, it doesnt throw anything itself.

  • @trhdbrave
    @trhdbrave 7 місяців тому +5

    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 7 місяців тому +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 7 місяців тому

      Thanks for your comment, so useful

    • @Anbaraen
      @Anbaraen 7 місяців тому

      Do you have any recs for the "right" way to do testing in JS?

    • @Aliena92
      @Aliena92 3 місяці тому

      @@keithjohnson6510 would you please recommend a video/tutorial to learn the error handling an easy/right way?

    • @Aliena92
      @Aliena92 3 місяці тому

      would you please recommend a video/tutorial to learn the error handling an easy/right way?

  • @ruanmoreiraofc
    @ruanmoreiraofc 7 місяців тому +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 7 місяців тому +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 7 місяців тому +27

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

    • @IvanRandomDude
      @IvanRandomDude 7 місяців тому +7

      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  7 місяців тому +2

      haha error handling gets really complicated really quickly

    • @keithjohnson6510
      @keithjohnson6510 7 місяців тому

      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 7 місяців тому

      Why I do not use async await

    • @natescode
      @natescode 7 місяців тому

      Please GOd no 😭

  • @rembautimes8808
    @rembautimes8808 7 місяців тому +1

    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

  • @gamingwolf3385
    @gamingwolf3385 7 місяців тому +3

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

  • @xpamamadeus
    @xpamamadeus 7 місяців тому +1

    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 7 місяців тому +2

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

    • @KDEDflyr55
      @KDEDflyr55 7 місяців тому

      purify-ts. It’s fantastic if you want monads without having to go deep with fp-ts

    • @snatvb
      @snatvb 7 місяців тому

      @@KDEDflyr55 Thanks, I'll keep that in mind.
      Actually fp-ts has them serializable, which I like, because structure is just data.

  • @VinnyXL420
    @VinnyXL420 7 місяців тому

    @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 7 місяців тому

      -> 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 7 місяців тому +1

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

  • @PieterMoeyersons
    @PieterMoeyersons 7 місяців тому +2

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

  • @naranyala_dev
    @naranyala_dev 7 місяців тому

    kind of few people talk about it, thank you

  • @rodjenihm
    @rodjenihm 7 місяців тому +5

    1:56 C# does not have checked exceptions

    • @JamesQQuick
      @JamesQQuick  7 місяців тому +1

      Ah good catch. Someone else called that out as well. Thanks for clarifying!

  • @ChristianKolbow
    @ChristianKolbow 7 місяців тому +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  7 місяців тому +1

      Ah good catch! Thanks!!

  • @dan110024
    @dan110024 6 місяців тому

    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.

  • @siya.abc123
    @siya.abc123 7 місяців тому

    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

  • @valenciawalker6498
    @valenciawalker6498 7 місяців тому

    Thank you!

  • @damonholden
    @damonholden 7 місяців тому +3

    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 7 місяців тому

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

  • @troooooper100
    @troooooper100 6 місяців тому

    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 ,

  • @RockTheCage55
    @RockTheCage55 7 місяців тому

    excellent....thanks

  • @darawan_omar
    @darawan_omar 7 місяців тому

    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

  • @vivekkaushik9508
    @vivekkaushik9508 7 місяців тому

    These thumbnails are getting crazy 😂. Nice vid tho.

    • @JamesQQuick
      @JamesQQuick  7 місяців тому

      haha yeah. Any suggfestions?

  • @jonathangamble
    @jonathangamble 7 місяців тому

    Still haven't tried Valibot?

  • @jsvrs
    @jsvrs Місяць тому

    tbh, i don't like this way. I'd prefer:
    const [ data, error ] = someFunction();
    and handle the error inside the function.

  • @victorhenriquecollasanta4740
    @victorhenriquecollasanta4740 7 місяців тому

    Error handling is time consuming and make the code ugly, I wish that we had a cleaner way to do it

    • @keithjohnson6510
      @keithjohnson6510 7 місяців тому

      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 7 місяців тому +1

    why just not to throw an err

    • @JamesQQuick
      @JamesQQuick  7 місяців тому

      In which scenario specifically?

    • @shakapaker
      @shakapaker 7 місяців тому

      @@JamesQQuick instead of object with error

    • @victorhenriquecollasanta4740
      @victorhenriquecollasanta4740 7 місяців тому

      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.