Node.js
Putting it together
Combine all parts into a working API.
Putting it together
The final lesson is integration: we combine all pieces (data model, Express, routes, middleware) into one working API. We also add an error middleware.
In Express, error middleware is defined with four arguments: (err, req, res, next). This signature tells Express it is an error handler. Errors thrown from routes or passed with next(err) land here. You return the error message to the client with res.status(500).json({ error: err.message }). 500 means “Server error”. This lesson is the last piece that makes the API production-ready, because errors are handled in a controlled way.
The error middleware signature
Express tells an error middleware from a normal one by the argument count. A normal middleware takes 3 arguments (req, res, next); an error middleware takes 4 (err, req, res, next).
If you write an error middleware with 3 arguments, Express treats it as a normal middleware and errors never reach it. So writing four arguments, with err first, is mandatory. When an error occurs, Express calls this middleware and passes the error object as err. err.message gives the error message. You set the server error code with res.status(500) and send the response with .json(). This way the app does not crash on unexpected errors.
Exercise Add an error middleware
Define an error middleware. Make it a four-argument function (err, req, res, next). Send the error response with res.status(500).json({ error: err.message }). The middleware must come AFTER the routes. The self-request is ready.
Show example solution
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});
Test yourself
-
Match each piece to its role
- err
- Error object
- res.status(500)
- Server error code
- err.message
- Error message
- 4 arguments
- Error middleware marker
-
How many arguments does an Express error middleware take?
(err, req, res, next)
Show answer
4 — Error middleware takes 4 arguments; this signature marks it.
-
Set the status code
res.____(500).json({ error: err.message });
Show answer
res.status(500).json({ error: err.message });
Next lesson: npm install