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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
do you absolutely hate writing try catch statements everywhere in javascript hey everyone it's kyle from gravity here and today i want to share with you a really exciting little bit of javascript um it means that you'll never have to write another try catch statement ever again for this tutorial we're going to need a few things um i've got a node.js application set up uh i've got my server here i'm using express js but this will work with anything so whether you're using next or something different that's okay but i'm using express i've got a very basic server set up here so import express create my app for the config and then i start my server um i've also imported an api file here and if i go over my second file here got a very basic api file here where i've created a post endpoint this is the endpoint we're going to use today and then this endpoint is going to be handled by a method in our auth controller which i've got here in my third file and this doesn't really do anything at the minute so we're just going to use this as a template to look at some error handling in javascript so i've got my server whoops i've got my server running i'm using postman here just to demonstrate how this would work so obviously in a real example you would be using a web app here um i'm just using this so you can see what's going on so if i send this request you can see my server is working so all i'm doing here is sending a post request to this endpoint that we've created and i'm passing through the what i'm going to do here is just email so i'm just going to pass through an email and password as if we're mimicking a standard login form so what's happening here is once this endpoint has been hit by postman it's going to call this uh method here in our auth controller function so at the minute this doesn't do anything but let's um let's add in some code here so one of the first things you might do whenever you're trying to authenticate a user is check that the user actually exists so what i'm going to do here is add in a database query to check if this user exists in my database typically i wouldn't write uh database queries directly in a controller like this but for the purpose of this tutorial this will keep things simple so let's go db user select id okay so whenever i run this it should go unfair oh yeah i haven't logged it out so let's log this out okay so from this query it's went and made a database call using the email address that i've passed in here and it's it's find that user so let's see what happens if i change this to username so what what should happen is this doesn't exist so it's going to try and make this um it's going to try and make this database so it's going to perform this database query but this doesn't exist so we should get an error message okay so you can see i've got javascript message error message on my server here and the request is now just hanging because we haven't properly handled um this error so what we should do is wrap this code in a try try catch statement so and we'll so what we're going to do is try to make this call if it if it works we will send 200 status back to the client it doesn't work we will catch the error and then send a 500 message back to the client so it is okay so you can see we've now caught the error we've handled the error and we've sent a response to the client now this is typically what most people do when they're they're handling errors in javascript the problem with this for me is i don't like first of all i don't like the way this looks all over the place it's also a massive pain to have to write these try catch statements ever everywhere so we're doing this in one function here but if we actually look at some of these other controllers that i have set up there's a lot of code here there's a lot of different functions um and there's a lot of different controllers so we don't want to have to write try catch in every single javascript function that we set up in node.js so what i'm going to do today is show you how to avoid having to use these anywhere so let's get rid of these and we'll keep this so i want to create an error so what i'm going to do is wrap this this function call in a higher order function so the best place to do this is in my api so i'm going to go back to my api file and i'm going to define this function here so this is a higher order function which basically just means it's a function that we're going to use to wrap all our other function calls in so here i'm just creating a function called use and we're going to pass it three parameters which is our request response and next object which will get past um a standard from our from the express function here and this function is basically just going to call the function that we pass into wrap it in a promise and then if there's an error catch it pass the error to next so next is also an express handler which just means pass it to the next uh function in the chain this may be quite difficult to get your head around you don't need to understand how this works actually i'll put the code in the description below and you can just copy and paste this um what i'm going to do next is use this function then to wrap all my api calls the reason i'm doing it in the api is because this is the highest level point in the application so when the client when a client makes a request it's going to hit one of these api endpoints so if i wrap the controller function in this this is going to handle all of the any errors that occur within this function and if even if i call other functions within that function so if i'm making a request to a model then this will they will any errors that occur will also be handled by this higher order function so the final thing that we have to do then is is handle what happens when when we hit this next so this is going to execute this function if there's an error it's just going to pass it along the chain so if we go back to our server i'm just going to create a global error handler which is going to take four oops it's just going to take four parameters so we've got our error request response and next so here you can see if i do i can log out our error and then i can also return the status here so so now what's going to happen is what should happen is when i run this code so there we go you've seen that we've caught the error here and we've sent back the 500 status with the message something went wrong could of course pass back error message um but in this example where we've got a mysql error i wouldn't recommend passing that back to the user what we would maybe do here is do some uh parsing to check if it's mysql error and then notify the user or some kind of generic error message because this is not going to be much help to them and this also reveals uh how our table is structured so it's a bit of a security issue so with this function here this means that we can now handle all of our errors with these four lines of code there's no there's no need for any try catch anywhere in your application because all of the requests are going to hit your api this higher order function is going to execute these functions here as long as they're wrapped in this use function so that's this use function it's going to create a promise execute this function here so no try catch here at all we've got an error because this doesn't exist and so this is going to throw an error it's going to be caught here and then we're going to pass it along the chain and it's going to get caught here in this global error handler so this means that you don't need to use try catch anywhere um say you wanted to change the error message you want to change that what you were sending back to the client let's say we wanted to return another something else like to the client we only have to do this in one place if we were using try catch we'd have to go through potentially hundreds of files hundreds of methods and and change how we handled those errors so that's it for today hopefully that was useful hopefully this is going to save you a lot of time that this saves me a huge amount of time because i don't have to think about writing try catch statements anywhere um you know it's also dangerous if you if you forget to write a try catch statement sometimes it can just slip your mind that you need to write one in a specific place you forget to do it and then obviously what's going to happen here is you're you're going to have an unhandled error your application is going to fall over and then the user is going to have a bad experience whereas with this the air is always going to be caught it's going to be handled and you're sending a response back to the user to let them know that something's went wrong that's it for today i hope you enjoyed the video hope you find it useful if you did please like subscribe share the video i know it's been a while since i've posted any of these and my plan is to get back into posting these out on a regular basis thank you very much you
Info
Channel: Gravity
Views: 43,007
Rating: undefined out of 5
Keywords: nodejs, javascript, error handling, try...catch, web application, saas, js, api, node, web development
Id: s5YoXms0ECs
Channel Id: undefined
Length: 11min 46sec (706 seconds)
Published: Sun Feb 07 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.