This repo contains a barebones API that tracks a list of notes. In this guided practice, you'll set up error handling middleware and refactor the existing routes into a separate router.
- Create a new repository using this one as a template.
- Clone down your repository and run
npm installto install the dependencies. - Start the development server with
npm run dev. - Test the requests in
.http. They should all be working, except for the POST request!
-
Right before
app.listen, add a catch-all middleware that callsnextwith a status of 404 and the message "Endpoint not found". This will be the default 404 middleware.See solution
app.use((req, res, next) => { next({ status: 404, message: "Endpoint not found." }); });
-
Right after your new 404 middleware but before
app.listen, add a default error-handling middleware. Log the error to the console withconsole.error. The response status should default to 500, unless the error has a status. Similarly, the response message should default to "Sorry, something went wrong!", unless the error has a message.See solution
app.use((err, req, res, next) => { console.error(err); res.status(err.status ?? 500); res.json(err.message ?? "Sorry, something went wrong!"); });
-
The handlers for
GET /notes/:idandPOST /notesdirectly send an error response when the request fails. Refactor them to callnextinstead with the corresponding status and message.See solution
- res.status(404).send(`Note with id ${id} does not exist.`); + next({ status: 404, message: `Note with id ${id} does not exist.` });
- res.status(400).send(`New note must have text.`); + next({ status: 400, message: `New note must have text.` });
-
Add middleware near the top of the file to parse JSON. The
POSTrequest in.httpshould now work.See solution
app.use(express.json());
At this point, every request in .http should work. Add more requests to make sure errors are handled correctly!
-
In
api/notes.js, create a new Express Router and export it.See solution
const express = require("express"); const router = express.Router(); module.exports = router;
-
Remove the
notesimport fromserver.js. Import thenotesarray intoapi/notes.jsinstead.See solution
const notes = require("../data/notes");
-
Move the 3
/notesmiddleware fromserver.jsintoapi/notes.js. Use theroutervariable instead ofapp, and remove/notesfrom the path of each middleware.See solution
router.get("/", (req, res) => { // unchanged }); router.get("/:id", (req, res, next) => { // unchanged }); router.post("/", (req, res, next) => { // unchanged });
-
In
server.js, where the/notesmiddleware used to be, add middleware to route/notesto the router exported fromapi/notes.js.See solution
app.use("/notes", require("./api/notes"));
-
Test the requests in
.httpto ensure that they all still work.
The final solution code can be viewed in the solution branch of the starter repository.