Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Practice Error Handling in Express!
You have completed Practice Error Handling in Express!
Preview
This video covers one solution to the error handling challenge.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Hey, how'd it go?
0:00
Were you able to figure out
how to handle those errors?
0:01
If not, that's okay.
0:03
Error handling can be one
of the more tricky and
0:04
challenging aspects of
server-side development.
0:06
Here's how I went about
completing the exercise.
0:09
First, the 404 handler in app.js.
0:12
I set the HTTP status for the response to
404 and rendered the not-found template.
0:16
Next, right below in
the global error handler,
0:23
I created an if statement to check for
the error status.
0:26
if (err.status === 404),
I set the res.status to 404 and
0:30
rendered the not-found template,
passing it the err object.
0:35
Else I set the err.message
to the given err.message, or
0:40
a general default error message.
0:44
Remember, any error message defined in
your route handlers will be used here.
0:47
Otherwise the error message will be, "oops,
0:51
it looks like something
went wrong on the server."
0:53
Then I set the error status to err.status,
or 500,
0:55
and rendered the error template,
also passing it the err object.
1:00
Now, when users land on
the quotes/error route, and
1:06
a status 500 server error's thrown by
default, the app displays the error view.
1:10
Finally, in routes/quotes.js, and down
in the GET id route handler, I created
1:17
an if statement to check if the requested
quote exists using its id parameter.
1:23
If it exists, the provided
res.render method gets called,
1:30
else I created a new error,
then set it status to 404,
1:34
provided a friendly error message and
called next(), passing it the new error.
1:39
This way, navigating to a quote that
doesn't exist results in a 404 page not
1:45
found view, displaying the err and
stack trace rather than an error view.
1:51
Again, if any error other
than a 404 error occurs,
1:56
the app displays the error view,
displaying the status 500 server error.
2:01
And if I make a request to some other
page or route that doesn't exist,
2:06
I get the 404 page not found view.
2:10
I hope that you were able to complete
this practice session successfully.
2:14
If not, you can always try it again
without looking at my version.
2:17
You're also going to get lots of other
opportunities to work with Express
2:20
throughout our JavaScript curriculum.
2:24
Thanks everyone, and happy learning.
2:26
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up