Hate Try...Catch Error Handling in Node.js? Do This Instead

Sdílet
Vložit
  • čas přidán 6. 02. 2021
  • UPDATE: At 8:32 you should replace the generic string with err.message to send a dynamic error message to the client.
    Are you fed up writing try…catch in your Node.js application?
    In this video I’ll show you how to set up a global error handler in a Node.js application in a few easy steps.
    You will never have to write another try…catch statement again!
    This trick will save you from writing hundreds of lines of unnecessary code.
    The tutorial uses Express.js but this technique will work with any framework and an API. It’s simply a higher order function (HOF) that wraps around your function calls to catch errors.
    QUESTIONS
    Have a question about error handling in Node.js? Please a comment below and I’ll get back to you.
    CONNECT
    Follow me on Twitter 👉 / kylegawley
    Find out more about Gravity 👉 usegravity.app
    SUBSCRIBE
    Get notified of new video tutorials 👉 / @gravityjs
  • Věda a technologie

Komentáře • 70

  • @mysteriousmsn
    @mysteriousmsn Před 2 lety +1

    Great Video, no try catch needed anymore, short and simple alternative.

  • @celebrate1989
    @celebrate1989 Před 3 lety +1

    Subscribed.. Please continue to do more videos on Node. Thanks

  • @joelr8481
    @joelr8481 Před 3 lety +5

    I was just researching this yesterday. I like the idea of HOF, so I'll give it a test.
    For completeness, you might want to have shown how to manage granular error responses.
    There are some valid error responses that need to make it back to the user. For my project, I take advantage of throwing as quickly as possible on the first sign of an error, and using classes extended from Error that take an error code and payload. Once this error reaches the app.use for error handling, it sends the response itself. This way you can keep your app.use code very small, but still support complex error handling.
    Thanks for the HOF tip!

    • @GravityJS
      @GravityJS  Před 3 lety

      Thanks, Joel! I usually will throw in a controller and pass a custom message, which then gets picked up by app.use and returned to the client (always trying to avoid passing the generated error).

    • @arthurlewin1952
      @arthurlewin1952 Před 6 měsíci

      How does it works behind the seen and there is one more doubt when I send the response code 500 it does not triggers the catch block of an async request

  • @ahmadkhudai
    @ahmadkhudai Před 2 lety

    bro this is so nice👍 this is going to save lives!

  • @pratiik37
    @pratiik37 Před 3 lety +1

    Thanks for the video✨

  • @thevietphung6967
    @thevietphung6967 Před 2 lety

    Thank you so much your video helped me understand things that my lecturer didn't explain to me. Thanks again ❤

  • @leoMC4384
    @leoMC4384 Před 2 lety +1

    Very useful. I'd add a fifth argument to the high order function: data about the operation, for logging in case of an error. Thank you. Great tutorial. 👏👏👏

    • @GravityJS
      @GravityJS  Před 2 lety

      Thank you

    • @RyanGosselin-xe9tl
      @RyanGosselin-xe9tl Před rokem +1

      Do you have a code example of this suggestion? Im new to JS

    • @josephajibodu2377
      @josephajibodu2377 Před 7 měsíci

      You can instead create custom exception classes with message, status code and data. That way its cleaner.

  • @guillermosalguero3581
    @guillermosalguero3581 Před 2 lety +1

    Great video, keep up the great work!

  • @mrtourist8066
    @mrtourist8066 Před 3 lety +2

    Thanks a lot for this informative and helpful video .😃

  • @dav.R7
    @dav.R7 Před rokem +1

    @Gravity . I really liked your solution, it worked perfect here. But wouldn't it be better to write function as handler than use?

  • @fakeplay4534
    @fakeplay4534 Před rokem

    Very good video!

  • @alexandryurkov9168
    @alexandryurkov9168 Před 3 lety +1

    Dude, this thing is awesome, thank u

  • @germanoller4418
    @germanoller4418 Před 8 měsíci

    really good work brother

  • @krishnachandrasharma1321

    It’s helpful 👍

  • @AlTearjen
    @AlTearjen Před rokem +3

    thanks for explaining this, but I don't think you should be saying every error is a 500 error. It could be a bad request. I would suggest this code. res.status(err.status || 500);
    res.end();

  • @huaquanghuy3998
    @huaquanghuy3998 Před 3 lety +1

    Thanks you for awesome video

  • @v0nnyboy
    @v0nnyboy Před rokem +5

    Couldn't one just use the 'express-async-errors' library ? Just wondering !!

    • @frosty129
      @frosty129 Před rokem +2

      I think that's an even better solution, no?

  • @icheston
    @icheston Před 2 lety

    What about chaining different handlers, if the catch calls the next middleware and the next middleware is to handle email notification. Even if there is an error, the email will get send?

  • @djmonteur
    @djmonteur Před 2 lety

    many thanks

  • @RyanGosselin-xe9tl
    @RyanGosselin-xe9tl Před rokem

    Cool. Hope my bootcamp teacher approves haha

  • @flowerofash4439
    @flowerofash4439 Před 2 lety +2

    interesting how the fn function return it self as a promise and somehow it is connected to the express route

  • @adventurer2395
    @adventurer2395 Před 2 lety +4

    Great video! One drawback of this approach is that you lose complete control over creating contextual errors at different layers of your app, which improves debugging, because you’re never catching/handling them and just bubbling up anything that might happen.

    • @GravityJS
      @GravityJS  Před 2 lety +2

      You can throw a specific error anywhere the catch it in this method. I messed up the video by passing a generic message back to the client and put a note in the description. Will do an updated video soon :)

    • @angrysmilex
      @angrysmilex Před 2 lety

      Just throw new Error('This is new error') in if else statement in any function

    • @dav.R7
      @dav.R7 Před rokem

      it was a good observation. I used the Joi library and I can't put the code status as 400.

    • @kakam458
      @kakam458 Před rokem +1

      You can still do independent try catch blocks if you need to.
      Also you can create custom error classes by inheriting the Error class. Then throw those instead. Like:
      class BadRequest extends Error{
      constructor(message){
      message = message || 'Unspecified Bad request';
      super(message);
      this.status = 400;
      }
      }
      throw new BadRequest();

  • @sheldonfourie5959
    @sheldonfourie5959 Před 2 lety +1

    On your front-end like vue what do you recommend doing for your api? can you recommend any good docs on this or repos I can check out?

    • @GravityJS
      @GravityJS  Před 2 lety +1

      To make the API calls? I use AXIOS.

    • @sheldonfourie5959
      @sheldonfourie5959 Před 2 lety +1

      @@GravityJS how you handle your errors neatly on the front-end

    • @galactusclb5733
      @galactusclb5733 Před 2 lety +1

      @@sheldonfourie5959 That's what I'm also looking for😊
      ex : When using SQL, how to handle errors in the best way. like user input errors ( duplicate entries), coding errors.
      if (err) {
      if (err.code === 'ER_DUP_ENTRY') {
      throw new BaseError("Duplicate entry.....................", err, "sampleFunc");
      }

  • @kabapy2
    @kabapy2 Před 2 lety +1

    i am trying to implement this on a higher level, on the express router level, it works for non-async-routes, and fails for async routes . any insights ??

    • @bonsayeb9620
      @bonsayeb9620 Před rokem

      Hey, I'm facing the same issue, did you find out a solution?

  • @roccodenicolo3921
    @roccodenicolo3921 Před 3 lety +2

    Thx for the video but I think in this way you just put all the different possible errors under '500+ general message'.
    Imagine we are developing a registration endpoint. maybe the problem could be that the user is trying to use a username that is used yet. In that case, the user will become back 500 'something went wrong' and he'll never understand how to fix the problem.
    is it my doubt right or I'm missing something in the workflow?

    • @GravityJS
      @GravityJS  Před 3 lety +2

      Hey Rocco, the ‘something went wrong’ was just an example. You can throw an error with a custom message, like:
      throw { message: ‘You are already registered’ }
      and this will be caught and sent back to the user, so they will know exactly what problem is.

    • @MatthewMcGuff
      @MatthewMcGuff Před 3 lety +1

      IMO, when you are building an API you want quick responses success or failure. Having a global error handler like this ensure that no matter what happens your client quickly knows where there is a success or failure. Perhaps one could decided whether to log errors to API calls based upon environment variables. If dev you could send all errors to the client as this is very helpful in debugging an application. In prod these wouldn't show.
      Great video. This was exactly what I looking for.

    • @sheldonfourie5959
      @sheldonfourie5959 Před 2 lety

      Also don't give the client to much info on what happened, always say the username or password you have entered is wrong as this is something attackers can use

  • @DR-ee4wv
    @DR-ee4wv Před 2 lety

    Man u r damn useful 🥰🥰🥰🥰

  • @npc73x
    @npc73x Před 2 lety +1

    What if I have a 4 middlewares and the error happened on 3 rd middleware ?

    • @icheston
      @icheston Před 2 lety

      The third middleware will still gets called 😂

  • @mod7ex_fx
    @mod7ex_fx Před 2 lety

    great

  • @mrtourist8066
    @mrtourist8066 Před 3 lety +1

    Subscribers++ 😁

  • @aliadel1723
    @aliadel1723 Před rokem

    bro sorry but can tell me how I can use it in any code and where in MVC??

  • @Ceghap
    @Ceghap Před 2 lety

    why not use a middleware instead of HOF?

    • @GravityJS
      @GravityJS  Před 2 lety

      Middleware is chained, it will execute after function.

  • @dkruger9553
    @dkruger9553 Před 2 lety +2

    You could also use a tryToCatch function like the one in this video: czcams.com/video/aAQnjcx5iug/video.html

  • @harshshah3797
    @harshshah3797 Před rokem

    Video starts at 4:52

  • @prerakhere
    @prerakhere Před 3 měsíci

    vid starts at 5:30

  • @johnjiang4412
    @johnjiang4412 Před rokem +1

    unneccesory background music

  • @jabborsattarov4982
    @jabborsattarov4982 Před rokem

    👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍

  • @edwinmunguia2049
    @edwinmunguia2049 Před 9 dny

    why are you complicating yourself? you just need to implement the error middleware and throw errors from controllers 🤷🏽

    • @GravityJS
      @GravityJS  Před 9 dny

      That's exactly what I did in the video.

  • @abdirahmann
    @abdirahmann Před rokem +1

    i get your solution, its beautiful but how do i implement it for middlewares that need to execute a 'finally' after the try catch has ended. i need the finally part because for some middlewares i want to do a db transaction (i don't use ORMs), i use postgres and that involves checking out a client from the pool and the *finally* releasing it into pool after a transaction has completed. i'll give you an example:
    const client = await pool.connect()
    try {
    // very may queries are executed here
    res.status(201).json({message: "resource created successfully"})
    } catch(err) {
    res.status(500).json({message: "something went wrong"})
    } finally {
    // here is how i would like to be helped. Thanks :)
    client.release()
    }
    .... more code