Start learning free

LESSON 157 OF 173 · BACKEND: BACKEND WITH AI

The AI Forgot the Missing Case in JavaScript

Practice

An AI assistant wrote the product page for this shop. Its handler asks the database for one product and answers its name, its price and whether it is in stock. Here is the AI's version:

app.get("/products/:productId", (req, res) => {
  const productId = Number(req.params.productId);
  const row = db.prepare("SELECT * FROM products WHERE id = ?").get(productId);
  res.json({ name: row.name, price: row.price, in_stock: row.stock > 0 });
});

It works for every product that exists. But when no product has the id, .get(...) gives undefined, and row.name crashes with a TypeError. Express answers 500 Internal Server Error with an HTML page. The AI wrote the happy path and forgot the missing case.

The fix is a check that runs before the code uses the value. Here it is on another route, for coupons kept in an object:

app.get("/coupons/:couponCode", (req, res) => {
  const coupon = COUPONS[req.params.couponCode];
  if (coupon === undefined) {
    return res.status(404).json({ error: "Coupon not found" });
  }
  res.json(coupon);
});

A 404 says "there is no such thing", in JSON the client can read. The return stops the handler there, so the last line never runs for a missing coupon. Your code must give these answers:

GET /products/1   →  200  {"name": "Mug", "price": 12, "in_stock": true}
GET /products/2   →  200  {"name": "Notebook", "price": 7, "in_stock": false}
GET /products/8   →  200  {"name": "Gift card", "price": 50, "in_stock": true}
GET /products/99  →  404  {"error": "Product not found"}
GET /products/0   →  404  {"error": "Product not found"}

Your task: rewrite the handler of GET /products/:productId. Ask the database for the product with this id. If there is no row, answer { error: "Product not found" } with 404; otherwise answer its name, its price and in_stock (true when the stock is above 0).


Assignment
Follow the Coding Tutorial to rewrite the product route with the missing case handled.


Hint
.get(...) gives undefined when no row matches. Check row === undefined before any line reads row.name, and start the 404 answer with return so the handler stops there.


STEP 1 OF 4
    Ctrl + Enter to check

    Ai Missing 404 in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free