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

Поделиться
HTML-код
  • Опубликовано: 25 дек 2024

Комментарии • 66

  • @soverain
    @soverain 9 месяцев назад +5

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

    • @JamesQQuick
      @JamesQQuick  9 месяцев назад +1

      Love it. What languages do you see that in?

    • @soverain
      @soverain 9 месяцев назад +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 9 месяцев назад

      @@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 9 месяцев назад

      @@nage7447 sure, but most implementations are good.

  • @marcusradell7544
    @marcusradell7544 9 месяцев назад +13

    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 9 месяцев назад +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 9 месяцев назад +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);

  • @rembautimes8808
    @rembautimes8808 9 месяцев назад +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

  • @trhdbrave
    @trhdbrave 9 месяцев назад +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 9 месяцев назад +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 9 месяцев назад

      Thanks for your comment, so useful

    • @Anbaraen
      @Anbaraen 9 месяцев назад

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

    • @Aliena92
      @Aliena92 5 месяцев назад

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

    • @Aliena92
      @Aliena92 5 месяцев назад

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

  • @ruanmoreiraofc
    @ruanmoreiraofc 9 месяцев назад +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. 2 месяца назад

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

  • @coffeeintocode
    @coffeeintocode 9 месяцев назад +27

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

    • @IvanRandomDude
      @IvanRandomDude 9 месяцев назад +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  9 месяцев назад +2

      haha error handling gets really complicated really quickly

    • @keithjohnson6510
      @keithjohnson6510 9 месяцев назад

      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 9 месяцев назад

      Why I do not use async await

    • @natescode
      @natescode 9 месяцев назад

      Please GOd no 😭

  • @ChristianKolbow
    @ChristianKolbow 9 месяцев назад +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  9 месяцев назад +1

      Ah good catch! Thanks!!

  • @gamingwolf3385
    @gamingwolf3385 9 месяцев назад +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 9 месяцев назад +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.

  • @VinnyXL420
    @VinnyXL420 9 месяцев назад

    @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 9 месяцев назад

      -> since most API's just throw the damn errors Correct, and that's how it should be if the error is an exception.

  • @snatvb
    @snatvb 9 месяцев назад +2

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

    • @KDEDflyr55
      @KDEDflyr55 9 месяцев назад

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

    • @snatvb
      @snatvb 9 месяцев назад

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

  • @naranyala_dev
    @naranyala_dev 9 месяцев назад

    kind of few people talk about it, thank you

  • @georgipetkov9080
    @georgipetkov9080 9 месяцев назад +1

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

  • @rodjenihm
    @rodjenihm 9 месяцев назад +5

    1:56 C# does not have checked exceptions

    • @JamesQQuick
      @JamesQQuick  9 месяцев назад +1

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

  • @PieterMoeyersons
    @PieterMoeyersons 9 месяцев назад +2

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

  • @siya.abc123
    @siya.abc123 9 месяцев назад

    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

  • @maacpiash
    @maacpiash 9 месяцев назад

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

  • @dan110024
    @dan110024 8 месяцев назад

    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.

  • @valenciawalker6498
    @valenciawalker6498 9 месяцев назад

    Thank you!

  • @troooooper100
    @troooooper100 7 месяцев назад

    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 ,

  • @darawan_omar
    @darawan_omar 9 месяцев назад

    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

  • @RockTheCage55
    @RockTheCage55 9 месяцев назад

    excellent....thanks

  • @damonholden
    @damonholden 9 месяцев назад +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.

  • @vivekkaushik9508
    @vivekkaushik9508 9 месяцев назад

    These thumbnails are getting crazy 😂. Nice vid tho.

    • @JamesQQuick
      @JamesQQuick  9 месяцев назад

      haha yeah. Any suggfestions?

  • @jonathangamble
    @jonathangamble 9 месяцев назад

    Still haven't tried Valibot?

  • @victorhenriquecollasanta4740
    @victorhenriquecollasanta4740 9 месяцев назад

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

    • @keithjohnson6510
      @keithjohnson6510 9 месяцев назад

      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.

  • @jsvrs
    @jsvrs 2 месяца назад

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

  • @shakapaker
    @shakapaker 9 месяцев назад +1

    why just not to throw an err

    • @JamesQQuick
      @JamesQQuick  9 месяцев назад

      In which scenario specifically?

    • @shakapaker
      @shakapaker 9 месяцев назад

      @@JamesQQuick instead of object with error

    • @victorhenriquecollasanta4740
      @victorhenriquecollasanta4740 9 месяцев назад

      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

  •  9 месяцев назад

    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.