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
We've dealt with connection errors but there are other things that could go wrong. Let's see if we can catch the other errors that could happen.
Documentation
-
0:00
Let me show you another error that can occur.
-
0:03
If you visit my profile endpoint at teamtreehouse.com/chalkers.json
-
0:09
we see a beautiful JSON file application, and we can work with this.
-
0:14
Well, what about if we go to another profile that doesn't exist, like
-
0:20
https://teamtreehouse.com/chalkers-not and hit Enter.
-
0:31
There's the text not found.
-
0:32
The text not found is not a valid JSON object.
-
0:38
Let's run the application with chalkers not as the username.
-
0:47
And this is the error that's displayed.
-
0:50
Our application is attempting to parse the string not found.
-
0:55
Not found isn't a valid JavaScript object.
-
0:59
That's why it say's unexpected token, meaning character n.
-
1:08
n is the first character it's trying to parse.
-
1:12
JSON files start with either an opening square bracket or curly braces.
-
1:19
Let's wrap the lines of code dealing with the parsing and
-
1:22
printing the message out with a try block.
-
1:37
Then we can catch the error and print it out.
-
1:51
Save the file.
-
1:55
And then rerun the application with an invalid username and
-
1:59
we don't get a stack trace anymore.
-
2:02
Once again, you can go ahead and include a more user-friendly message if you want.
-
2:08
Before we move on to the next error we handle,
-
2:11
since we're handling multiple errors, let's create a function that's
-
2:15
flexible enough to print out error messages from an error object.
-
2:20
Or any other object with a message property.
-
2:23
This means if we want to choose to implement how we handle errors differently
-
2:27
in the future, we only have to do it in one place.
-
2:39
Let's create a function PrintError.
-
2:45
That takes in one argument error.
-
2:57
And log out the error message.
-
3:00
Let's update where all the console.errors are with printError.
-
3:27
Awesome.
You need to sign up for Treehouse in order to download course files.
Sign up