Hate Try...Catch Error Handling in Node.js? Do This Instead
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
Great Video, no try catch needed anymore, short and simple alternative.
Subscribed.. Please continue to do more videos on Node. Thanks
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!
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).
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
bro this is so nice👍 this is going to save lives!
Thanks for the video✨
Thank you so much your video helped me understand things that my lecturer didn't explain to me. Thanks again ❤
You're welcome! :)
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. 👏👏👏
Thank you
Do you have a code example of this suggestion? Im new to JS
You can instead create custom exception classes with message, status code and data. That way its cleaner.
Great video, keep up the great work!
Thank you!
Thanks a lot for this informative and helpful video .😃
Welcome :)
@Gravity . I really liked your solution, it worked perfect here. But wouldn't it be better to write function as handler than use?
Very good video!
Dude, this thing is awesome, thank u
Glad you found it useful :)
really good work brother
It’s helpful 👍
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();
Thanks you for awesome video
You’re welcome :)
Couldn't one just use the 'express-async-errors' library ? Just wondering !!
I think that's an even better solution, no?
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?
many thanks
Cool. Hope my bootcamp teacher approves haha
interesting how the fn function return it self as a promise and somehow it is connected to the express route
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.
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 :)
Just throw new Error('This is new error') in if else statement in any function
it was a good observation. I used the Joi library and I can't put the code status as 400.
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();
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?
To make the API calls? I use AXIOS.
@@GravityJS how you handle your errors neatly on the front-end
@@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");
}
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 ??
Hey, I'm facing the same issue, did you find out a solution?
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?
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.
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.
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
Man u r damn useful 🥰🥰🥰🥰
Thank you :)
What if I have a 4 middlewares and the error happened on 3 rd middleware ?
The third middleware will still gets called 😂
great
Subscribers++ 😁
bro sorry but can tell me how I can use it in any code and where in MVC??
why not use a middleware instead of HOF?
Middleware is chained, it will execute after function.
You could also use a tryToCatch function like the one in this video: czcams.com/video/aAQnjcx5iug/video.html
Good one!
Video starts at 4:52
vid starts at 5:30
unneccesory background music
👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍
why are you complicating yourself? you just need to implement the error middleware and throw errors from controllers 🤷🏽
That's exactly what I did in the video.
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