Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
In this video we'll handle HTTP errors.
Documentation
STATUS_CODES
The STATUS_CODES
array is not on the https
object. STATUS_CODES
can be found on the http
object. To include the STATUS_CODES
use the following code:
const http = require('http');
http.STATUS_CODES;
-
0:00
We've assumed so far that each of the API responses will be OK.
-
0:05
In other words, have the HTTP status code of 200.
-
0:09
There are other status codes that an API endpoint can have.
-
0:13
Maybe there's errors in the code actually running on the server where the endpoint
-
0:17
is happening.
-
0:17
That's when you'd get a 500 error or internal server error.
-
0:22
Or maybe the API endpoint has been updated and has moved somewhere else.
-
0:26
You'd get the status code of 301.
-
0:29
If the endpoint is incorrect or has removed completely,
-
0:33
you'd get the HTTP status code of 404, not found.
-
0:39
Let's handle all status codes that aren't 200.
-
0:43
If the response .statusCode is equal
-
0:48
to 200, we want to do the parsing.
-
1:02
If the status code isn't 200,
-
1:06
we want to printout an error message for the status code.
-
1:12
So let's create a new
-
1:17
statusCodeError by creating
-
1:22
a new Error object,
-
1:26
with the message of a template string saying,
-
1:35
There was an error getting
-
1:41
the profile for ${username}.
-
1:52
Then we can add the status code in brackets.
-
1:59
We can print the error using the printError method that
-
2:04
we created earlier, passing in statusCodeError.
-
2:11
Save the file and open up the console.
-
2:15
And let's try and run node app.js chalkers-not.
-
2:24
And there's something wrong in my code.
-
2:32
I didn't close my else statement.
-
2:38
Run it again, and
-
2:43
we get the message there was an error getting the profile for chalkers-not,
-
2:47
with the status code of 404, not found.
-
2:51
You may know what 404 is being a web developer, and
-
2:55
you've probably seen it on many a site.
-
2:59
But what if the error was something else?
-
3:02
Is there a way to translate these error codes into something a human can
-
3:07
easily understand?
-
3:08
The HTTP module has a statusCodes object that
-
3:13
returns an English string from a status code.
-
3:24
Remember that we need to include the module at the top.
-
3:46
Let's try again, Awesome, it says not found.
-
3:55
Let's walk chalkers-not back to chalkers to make sure we haven't broken anything.
-
4:02
We haven't, cool.
-
4:05
Now that we've handled all the errors,
-
4:07
why not improve the messages that are generated by the printError function?
-
4:11
When you're done, I'll see you in the next video, and
-
4:14
I'll show you some techniques for organizing your code.
You need to sign up for Treehouse in order to download course files.
Sign up