Sometimes the server's own code fails. In this lesson the shop has a bug on purpose: the query in GET /api/orders asks for a column that doesn't exist, order_items.price. Right now Express answers with its own HTML error page. The storefront expects JSON, so it shows a confusing message: Unexpected token '<', "<!DOCTYPE "... is not valid JSON.
An error has two readers. You need the details: which request failed and why. The visitor only needs to know that it failed. So the details go to the server's log with console.error, and the answer says only {"error": "Something went wrong"}. The message, the SQL and the stack never go in the answer.
Express knows an error handler by its four parameters, (err, req, res, next). It skips the handler for normal requests and calls it when a route throws. Express looks for it below the route that failed, so it goes last: below every route and below the /api 404 handler. One handler covers every route. If a typo broke the SQL in GET /api/products tomorrow, that route would get the same plain 500.
After a login as ana@example.com, your server must answer:
POST /api/login {"email": "ana@example.com", …} → 200 {"email": "ana@example.com"}
GET /api/orders → 500 {"error": "Something went wrong"}
server log: GET /api/orders Error: no such column: order_items.price
On the Orders page, the visitor sees the alert Something went wrong and a Try again button.
Your task: in server/app.js, write handleError. It logs the method, the URL and the error, and answers 500 with the plain message. Register it with app.use below the 404 handler. Leave the bug in the orders query alone: it's there to test your handler.
Assignment
Follow the Coding Tutorial to write the error handler handleError in server/app.js and register it last.
Hint
Keep the four parameters in this order, with err first. If the page still shows "Unexpected token", check that app.use(handleError) comes below the routes.
Free plan: 30 tutor messages. PRO is unlimited.
