Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Now that we have a custom error handler, let's add a middleware function to handle 404 errors, and send them to the error handler.
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
A 404 signals that the user
requested a route that doesn't exist.
0:00
Remember, when an app gets a request,
0:05
it will go from one app.use call
to the next looking for a match.
0:08
If it gets to the end without finding
a route and there are no errors,
0:13
Express' native handler will send a 404
back to the client with some plain text.
0:19
If we catch the request before
it gets to the end of the line,
0:26
we can send users a better page.
0:30
Check out Treehouse's 404 page, or Lego's,
0:33
or my personal favorite, GitHub.
0:39
We can give our users
a less scary page too.
0:42
Let's write some middleware to
handle 404 errors in our app.
0:46
We want to access the request at the end
of our app and before the error handler.
0:51
So let's call app.use here.
0:58
We're going to use the error
handler we wrote in the last video
1:10
to handle the actual error.
1:13
This middleware will
just be responsible for
1:16
creating the error object and
handing off to the error handler.
1:19
I'll create a new error, Not found.
1:25
Then I'll set the error status code,
1:36
To 404,
Before parsing it to the next function.
1:42
Now, any requests that makes it
this far will run this function and
1:53
trigger the error handler.
1:58
The error handler itself will send
the page out to the user in that event.
2:01
Let's try it out.
2:06
In the browser,
I'll request a route that doesn't exist.
2:08
Voila, now when our users go astray,
they will get a friendlier notice.
2:16
We've covered the basics of Express now,
well done.
2:22
Let's cement your knowledge in
the remainder of this course by
2:25
finishing our flash card application.
2:28
Are you ready to apply your knowledge?
2:30
See you there.
2:33
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