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 REST APIs with Express!
You have completed REST APIs with Express!
Preview
A lot can go wrong in an application, and a big part of a developer’s job is to account for and gracefully deal with a variety of errors. We'll write a global error handler to send error messages to the client as JSON.
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
[MUSIC]
0:00
A lot can go wrong in an application, and
a big part of a developer's job is to
0:04
account for and
gracefully deal with a variety of errors.
0:08
We're already doing a decent job of that,
but
0:12
there are some things we can do that will
cut down on some of our repeating code.
0:14
There are two basic types of
errors we're dealing with,
0:18
stuff that went wrong with the request,
and stuff that went wrong with the server.
0:21
We're currently addressing
errors that occur, for
0:26
example, if the client makes a request
to a quote id that doesn't exist.
0:28
But look what happens when we
request a route that doesn't exist.
0:32
Go to post man and
0:36
send a request to local host slash
3,000 followed by some gibberish.
0:37
Now see what happens if you make
a request to a route that exists but
0:43
with an action we haven't accounted for.
0:46
For example,
we have no put route to slash quotes.
0:48
So I'll change this to put, send and
by default express sends a 404 Not Found
0:53
status code for routes that don't exist,
which is great.
0:58
But both times, Express sends us
some HTML containing an error.
1:02
We don't want to send HTML, though,
because a RESTful API sends JSON.
1:06
For our API, we're going to need to
create our own custom error handler so
1:11
that we can send the error
message as a JSON object.
1:15
We'll do that first by writing some
middleware that creates an error.
1:18
We'll then pass that error to
an express error handling function, and
1:22
that function will send
error messages as JSON.
1:25
Express middleware are functions that run
after a request comes in from the client
1:28
and before a response is sent.
1:33
Earlier, we used this middleware
which parses incoming JSON and
1:35
makes the data available
on the request body.
1:39
If you need a deeper
refresher on middleware,
1:42
see the links in the teacher's notes.
1:44
Middleware will run each time a request
comes in unless you specify otherwise.
1:46
To use middleware,
we can use expresses.use method.
1:51
Express will call middleware functions
in the order they've been added, so
1:56
we'll want to place this middleware
function below all of our other routes.
1:59
This way if a request comes in that
doesn't match any of these routes,
2:04
the request will fall into
this piece of middleware.
2:07
You can pass the use method,
the function that you want to add,
2:15
like we did with Express JSON above, or
you can pass it an anonymous function.
2:18
So if a delete request comes in to
quote/ID, that will trigger this method.
2:28
And it'll do its thing and
send back a response,
2:36
ending the request response cycle.
2:38
But if a delete request comes into
/quotes, well, we have nothing defined for
2:40
that type of request.
2:45
So no route would be triggered.
2:46
The request would thus end up here.
2:48
The next method triggered
will be this middleware.
2:51
Middleware needs to do one of two things.
2:54
It needs to end
the Request-Response cycle or
2:57
tell Express to move on to
the next middleware function.
2:59
That's why all Express middleware
takes a third parameter
3:03
which by convention is called next.
3:06
So into this anonymous function
we will do req, res, and next.
3:09
Inside this middleware, we'll use
JavaScript's built in error constructor.
3:15
This will create an error object and
to that object we can pass a string
3:23
describing the error,
we'll just say not found.
3:27
Finally, we call next and
into the next function,
3:31
we can pass in the error
we've just created.
3:35
So we actually need to save this
to a variable called error which
3:40
we're passing to the next function.
3:44
Calling next with a parameter signals
to Express that there's been an error.
3:47
Its next act will be to
call an error handler,
3:51
passing the parameter on to that handler.
3:54
Let's create that error
handler now just below.
3:56
Setting up a custom error handler
is exactly the same as setting up
4:01
middleware with one distinction.
4:04
Error handlers have four parameters.
4:06
So we can say app.use,
pass in our anonymous function
4:08
and our parameters are err,
req, res, and next.
4:16
Express will use the extra parameter
to pass the error object into.
4:23
That's the only way express knows
that this is an error handler.
4:28
The first parameter as you
can see is the error object.
4:32
If the error has a status property,
4:35
that's what we'll set the HTTP
status to in our response.
4:37
If the status property of
the error happens to be undefined,
4:46
we'll send HTTP status code 500.
4:51
So here we can say, or 500 and
a status property might be undefined for
4:53
example if this handler received
an internal server error.
4:59
Finally, we can send the error
to the client as json.
5:04
We will pass res.jason
an object containing an error
5:07
With our error message.
5:20
Let's test this out.
5:22
We'll go back to postman and send
a request to a route that doesn't exist.
5:24
Awesome, we're getting
that Not Found message.
5:30
But as you can see,
5:33
we're getting a 500 Internal Server Error
that we've set to be the default.
5:34
Remember, we did that because if something
does fall through as a server error,
5:38
it might have an undefined status.
5:42
So we just need to make sure in our
middleware that catches any request to
5:44
routes that don't exist that we're
changing the status code to 404.
5:48
If we test again, you can see that
we're getting our error message
5:56
in the form of JSON, and
the correct status code is being sent.
6:00
Let's simulate a server error by throwing
an error inside of the triblock of
6:04
our delete function.
6:09
Inside our catch block, instead of
manually changing the status code and
6:17
setting an error message as we are now,
6:22
we can simply pass the error to our global
error handler using the express function,
6:25
next, so let's delete this and
say next{err}.
6:30
We'll also need to add the next
parameter to our callback.
6:34
Because we're passing next at parameter,
Express knows to run our global
6:39
error handler next and
it will pass along the error message.
6:43
Let's test this out in Postman.
6:47
So we need to send a delete
request to /quotes and
6:51
we'll say quote the ID of 8721.
6:57
And we get the correct 500 status error
in our error message in the form of JSON,
7:01
great.
7:06
These two handlers offer us coverage for
7:07
a wide range of problems a client
might experience when using our API.
7:09
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