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

  Рет қаралды 44,814

Gravity

Gravity

Күн бұрын

Пікірлер: 70
@joelr8481
@joelr8481 3 жыл бұрын
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 3 жыл бұрын
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 11 ай бұрын
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
@v0nnyboy
@v0nnyboy 2 жыл бұрын
Couldn't one just use the 'express-async-errors' library ? Just wondering !!
@frosty129
@frosty129 Жыл бұрын
I think that's an even better solution, no?
@AlTearjen
@AlTearjen Жыл бұрын
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();
@mysteriousmsn
@mysteriousmsn 2 жыл бұрын
Great Video, no try catch needed anymore, short and simple alternative.
@leoMC4384
@leoMC4384 2 жыл бұрын
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 2 жыл бұрын
Thank you
@RyanGosselin-xe9tl
@RyanGosselin-xe9tl Жыл бұрын
Do you have a code example of this suggestion? Im new to JS
@joseph_oluwayomi
@joseph_oluwayomi Жыл бұрын
You can instead create custom exception classes with message, status code and data. That way its cleaner.
@flowerofash4439
@flowerofash4439 2 жыл бұрын
interesting how the fn function return it self as a promise and somehow it is connected to the express route
@RyanGosselin-xe9tl
@RyanGosselin-xe9tl Жыл бұрын
Cool. Hope my bootcamp teacher approves haha
@dav.R7
@dav.R7 2 жыл бұрын
@Gravity . I really liked your solution, it worked perfect here. But wouldn't it be better to write function as handler than use?
@celebrate1989
@celebrate1989 3 жыл бұрын
Subscribed.. Please continue to do more videos on Node. Thanks
@kabapy2
@kabapy2 2 жыл бұрын
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 2 жыл бұрын
Hey, I'm facing the same issue, did you find out a solution?
@npc73x
@npc73x 2 жыл бұрын
What if I have a 4 middlewares and the error happened on 3 rd middleware ?
@icheston
@icheston 2 жыл бұрын
The third middleware will still gets called 😂
@sheldonfourie5959
@sheldonfourie5959 3 жыл бұрын
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 2 жыл бұрын
To make the API calls? I use AXIOS.
@sheldonfourie5959
@sheldonfourie5959 2 жыл бұрын
@@GravityJS how you handle your errors neatly on the front-end
@galactusclb5733
@galactusclb5733 2 жыл бұрын
@@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"); }
@germanoller4418
@germanoller4418 Жыл бұрын
really good work brother
@icheston
@icheston 2 жыл бұрын
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?
@alexandryurkov9168
@alexandryurkov9168 3 жыл бұрын
Dude, this thing is awesome, thank u
@GravityJS
@GravityJS 3 жыл бұрын
Glad you found it useful :)
@roccodenicolo3921
@roccodenicolo3921 3 жыл бұрын
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 3 жыл бұрын
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 3 жыл бұрын
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 3 жыл бұрын
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
@mrtourist8066
@mrtourist8066 3 жыл бұрын
Thanks a lot for this informative and helpful video .😃
@GravityJS
@GravityJS 3 жыл бұрын
Welcome :)
@guillermosalguero3581
@guillermosalguero3581 2 жыл бұрын
Great video, keep up the great work!
@GravityJS
@GravityJS 2 жыл бұрын
Thank you!
@pratiik37
@pratiik37 3 жыл бұрын
Thanks for the video✨
@ahmadkhudai
@ahmadkhudai 3 жыл бұрын
bro this is so nice👍 this is going to save lives!
@adventurer2395
@adventurer2395 2 жыл бұрын
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 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 2 жыл бұрын
Just throw new Error('This is new error') in if else statement in any function
@dav.R7
@dav.R7 2 жыл бұрын
it was a good observation. I used the Joi library and I can't put the code status as 400.
@kakam458
@kakam458 2 жыл бұрын
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();
@thevietphung6967
@thevietphung6967 3 жыл бұрын
Thank you so much your video helped me understand things that my lecturer didn't explain to me. Thanks again ❤
@GravityJS
@GravityJS 2 жыл бұрын
You're welcome! :)
@huaquanghuy3998
@huaquanghuy3998 3 жыл бұрын
Thanks you for awesome video
@GravityJS
@GravityJS 3 жыл бұрын
You’re welcome :)
@fakeplay4534
@fakeplay4534 2 жыл бұрын
Very good video!
@abdirahmann
@abdirahmann 2 жыл бұрын
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
@aliadel1723
@aliadel1723 2 жыл бұрын
bro sorry but can tell me how I can use it in any code and where in MVC??
@krishnachandrasharma1321
@krishnachandrasharma1321 2 жыл бұрын
It’s helpful 👍
@harshshah3797
@harshshah3797 Жыл бұрын
Video starts at 4:52
@djmonteur
@djmonteur 3 жыл бұрын
many thanks
@Ceghap
@Ceghap 3 жыл бұрын
why not use a middleware instead of HOF?
@GravityJS
@GravityJS 3 жыл бұрын
Middleware is chained, it will execute after function.
@prerakhere
@prerakhere 8 ай бұрын
vid starts at 5:30
@DR-ee4wv
@DR-ee4wv 3 жыл бұрын
Man u r damn useful 🥰🥰🥰🥰
@GravityJS
@GravityJS 3 жыл бұрын
Thank you :)
@johnjiang4412
@johnjiang4412 Жыл бұрын
unneccesory background music
@mod7ex_fx
@mod7ex_fx 3 жыл бұрын
great
@dkruger9553
@dkruger9553 3 жыл бұрын
You could also use a tryToCatch function like the one in this video: kzbin.info/www/bejne/l3K0n52ZrZqcq8k
@sheldonfourie5959
@sheldonfourie5959 3 жыл бұрын
Good one!
@mrtourist8066
@mrtourist8066 3 жыл бұрын
Subscribers++ 😁
@edwinmunguia2049
@edwinmunguia2049 5 ай бұрын
why are you complicating yourself? you just need to implement the error middleware and throw errors from controllers 🤷🏽
@GravityJS
@GravityJS 5 ай бұрын
That's exactly what I did in the video.
@jabborsattarov4982
@jabborsattarov4982 Жыл бұрын
👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍
Error Handling in NodeJS (Complete Guide) | Node Tutorial
17:54
Nikita Dev
Рет қаралды 45 М.
JavaScript Error Handling: 5 Things You Aren’t Thinking About!
14:42
She made herself an ear of corn from his marmalade candies🌽🌽🌽
00:38
Valja & Maxim Family
Рет қаралды 18 МЛН
СИНИЙ ИНЕЙ УЖЕ ВЫШЕЛ!❄️
01:01
DO$HIK
Рет қаралды 3,3 МЛН
Что-что Мурсдей говорит? 💭 #симбочка #симба #мурсдей
00:19
5 Async + Await Error Handling Strategies
18:11
Wes Bos
Рет қаралды 24 М.
When is NodeJS Single-Threaded and when is it Multi-Threaded?
18:42
Hussein Nasser
Рет қаралды 74 М.
try, catch, finally, throw - error handling in JavaScript
5:46
freeCodeCamp.org
Рет қаралды 177 М.
Error Handling in Express
12:47
Jan Goebel
Рет қаралды 40 М.
Central Error Handling In NodeJS and TypeScript
11:11
WebDevLog
Рет қаралды 9 М.
How to handle Node.js errors like a Pro?
12:44
Software Developer Diaries
Рет қаралды 36 М.
She made herself an ear of corn from his marmalade candies🌽🌽🌽
00:38
Valja & Maxim Family
Рет қаралды 18 МЛН