Handling Errors & Improving the Project Setup | Creating a REST API with Node.js
Video Title: Handling Errors & Improving the Project Setup | Creating a REST API with Node.js
Welcome back to the serious over the last videos we already worked quite a bit on our restful api and I liked how it looked said works really great now we added some routes and zhan it’s now time to improve our development set up a little bit at least and I always want to
Make sure that we improve error handling because we’re not really handling errors in our API as of now so first of all what I want to improve regarding the setup is I don’t constantly want to restart the server whenever we make a change to anything for this we can use a package called
Node Mon we install it with the NPM install and then – – save def because 3 is only a development dependency we need and then the name is just node Mon just download it like this this is a package which will basically monitor your files and automatically restart the server
Whenever you change something a link to the package can be found in the video description and there you can learn more about it so now with that note one was added I now also want you no longer manually type note server but instead with node Mon we would have to type node
Mon server je s that however will fail because it’s not a global package installed on our machine now we can easily work around this by going to the package.json file and adding a script let’s add the start script that’s a special script we can easily execute by running NPM start inside our project
Folder and when we type this I want to run node 1 here I can use that because this will now not search for it on our cert system but in our project and there we just installed it so then I want to execute node 1 server je s now if I run
NPM start here you see we got this output here looks a little bit different than before and it essentially started our server so if I go back to postman and I try my requests again this still works because we got a no js’ server but watch the console if I added something
So here I’ll simply add a comment routes which should handle requests and now if I save this file you see it’s restarting the server even though here I didn’t add any logic that would have required that but it watched the file and saw that I changed it and
This all the works for files and subdirectories here if I say handle incoming get requests to slash orders and I save this it also restarted so this is really convenient now we don’t have to manually cancel the server and restart whatever make a change additionally I want to add a logging
Package to my set up to log incoming requests so that we can also see some information here in the terminal so for that I’ll temporarily quit node Mon and install another package with NPM install – – save and it’s called Morgan it’s a logging package for node J s we
Can use it really easy just go to app J s and there let’s create a new constant its name at Morgan and require the name is by the way totally up to you require Morgan this name is not up to you that has to be the package you
Installed and now we have to basically tell Express to funnel all requests through this middleware that it is in the end and Morgan will then just log something and let the request continue so Morgan behind the scenes will call this next function saying I don’t return
A response I just did something in this case I locked something you continue doing your work so let’s use Morgan and let’s use it before we handle our requests with our routes by simply saying app use and then use some more again as a function and pass death here
That’s the format we want to use for the output now with that let’s rerun NPM start to restart node Mon and if I now again send a request here it looked as before but you see now in a terminal we get this extra log seeing that we got a
Get request and how long it took and so on so that’s really nice additionally I now want to handle errors keep in mind if we send a request to some invalid ID or with some invalid HTTP word we get back this default error HTML page and I
Want to send back JSON instead now error handling is really nice in set up here keep in mind that we have here our middleware which forwards requests to products and orders files where we then have to router on the apprehend that means if we make it past these two middlewares
None of the routes set up an IVA of the two files were suited to handle the incoming requests hence we can handle errors by simply catching all requests that make it past these two requests here these two middlewares I should say so we can something use the app object
And now use and no longer add a filter like slash something but simply say I want to handle every request that reaches this line because if you reach that line it means no route in one of these two files was able to handle the request so here in this middle of where
I again have my request response and the next function and now I simply want to return an error here so I will create a new constant error and create a new error here the error object is available by default you don’t need to import it
Or anything like that and here I want to output not found as a error text I will also set a error status code excuse me that should be error so that error object is provided by no chase and I can set a status code of 404 because here we
Get here if we have an error because we didn’t find a fitting route which is the definition of a 404 error then I will actually execute this next method and pass my error along with it this will now forward the request but forward this error request here instead of the
Original one essentially now add another middleware here where I also get my request response and next but I get a separate first argument which actually is my error and this here will handle all kinds of errors like the error we create here and we for
Word or and that is why I chose this setup errors thrown from anywhere else in this application this shouldn’t really be able to happen yet but later when we add a database for example and when we have operations doing work on the database these operations could fail
And we then want to return a 500 error now if these operations fail they will directly throw an error so we don’t make it into this first middleware but since they throw an error this middleware here would be triggered and it would handle this error or get this error so here we
Can set a status code on the response we eventually want to send back which is either the status code the error has like it has if we created our 400 error 404 error or we assign a 500 error code for all other kinds of errors and then
We can simply return some JSON data here and we could have changed that as I did in the router setup so that would have worked too and there I want to send an error object which maybe should have a message property and this setup is
Totally up to you set it up as you want and there I will pass on my error message like the message this should also be error by the way the a message of the error we get as a first argument here the message will automatically be not found and for other errors
Whoops fix the typo for our errors these typically also have a message property it’s kind of what most errors have you can pretty much rely on them having a message object a message property and now we will return this so let’s try this out let’s save this and no daman
Will restart and now let’s again send an invalid request now you see we get back a method and our answer here error status is not a function it nicely proves that the automatically thrown error has a message property because that’s not our own error and I did indeed
Is up here we should assign an error status property of 404 not a method so now let’s try this again and now we get not found which again is our custom message this one and so I accidentally but it’s also kind of good I guess proved that though our custom 404 and
Ler SD I handle all other kinds of errors like my error with the unknown function here both work and with that we got automatic reloading we got default logging and we got error handling which is a great improvement to our project with that let’s leave it as
This and let’s go back into our project and make sure that we add more useful functionalities to it in the next videos
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
I did this whole tutorial about 3 years ago, still refer to it on occasion, as I am now. Love Max and Manu! ❤
nodemon replaced by mode –watch {filename}…version 18 and above
If your doesn't show the error, just restart the server
I like it, Sir.
SPEECHLESS 👌👌
Really love your videos! However I noticed that the middleware handling 404 Error also handles other errors like invalid http methods, …. I wonder if there is anyway to prevent that? (just handle 404 error only).
how did the 404 error and 500 or any 500 types error was shown by the code ??
Your courses and videos are just amazing!
I got error at req.body.images.length
The error is “cannot read the property ‘length’ of undefined”
Thanks max always improves my coding with your tutorials. ❤️
You are the best instructor on Udemy. I really enjoy your teaching method.
Why is morgan response time different than the one in postman?
is there any way to reduce errors when it comes to API calls?
I couldn't get nodemon to detect changes, but I found an alternative named "supervisor" (same setup) that works perfectly.
amazing!!!!!
Again and again Bro you are great did well.. very good explanation…. love you brother. 🙂
Thanks . Your videos are great!
this video helped me a lot. A lot of people made videos were I had to have 600 lines of copy pastaed app.get and app.post on index.js, now I have like 90 lines.
4 videos in and I just realized that there are no ads. Sir, I hope you get all the recognition you deserve!
so is it better to download as global instead or type individually? I love the detailed videos. Thank you for teaching us! XD
Sir I have little bit doubt about that , this error handling works with database or not…
Great tutorials as always.
Great teacher and I love your accent, sounds to me like you're saying serious and wizard instead of series and visit haha, I understand you very well though and you have good English though I guess it's not your first language :). Very informative videos!
Hey great explaination I just have one doubt wouldnt the error handler middleware executes for every request for ok as well as bad ones ?
So here instead of manually handling errors in try-catch blocks for every route we just define a middleware that handles all the errors and returns the result?
In terminal use npm start not nodeman server.js its not working might depracted.