Start learning free

LESSON 26 OF 173 · BACKEND: YOUR FIRST API

One Way to Send Errors in TypeScript

Practice

Your shop sends errors from six places, and each one builds { error: ... } by hand. A client relies on every error having the same shape: it reads the message under the key "error". One typo in one place, like "eror", and the client loses that message.

The fix is a helper function: an ordinary function that builds the answer in one place. It is not given to app.get or any other method, so it isn't a route; the routes call it. In Express an answer is sent through the route's res, so each route passes its own res, of type Response, to the helper, and the helper sends the answer. It gives nothing back, so its return type is void. A helper for success answers could look like this (not part of the shop):

function created(res: Response, item: object): void {
  res.status(201).json(item);
}

app.post("/notes", (req: Request, res: Response) => {
  const note = req.body;
  notes.push(note);
  created(res, note);
});

TypeScript checks every call against the helper's types: a text where the number goes is an error before the code runs. The answers stay exactly the same; only the code gets tidier. The requests and answers your code must give, in this order:

GET /products/9  →  404  {"error": "Product not found"}
POST /products  {"price": 5, "category": "kitchen"}
  →  400  {"error": "Name is required"}
POST /products  {"name": "Cup", "price": -1, "category": "kitchen"}
  →  400  {"error": "Price must be a whole number of 0 or more"}
DELETE /products/9  →  404  {"error": "Product not found"}
PUT /products/9  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  404  {"error": "Product not found"}
PATCH /products/9  {"price": 5}  →  404  {"error": "Product not found"}
POST /products  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  201  {"id": 5, "name": "Cup", "price": 5, "category": "kitchen"}
GET /products/5  →  200  {"id": 5, "name": "Cup", "price": 5, "category": "kitchen"}

Your task: write errorResponse(res: Response, message: string, status: number): void, which sends the JSON body {"error": message} with the given status, and use it for every error answer in the shop: the 404 of the GET, DELETE, PUT and PATCH routes for one product, and the two 400s of the POST route.


Assignment
Follow the Coding Tutorial to write the errorResponse helper and send every error through it.


Hint
The helper goes under notAllowedPage, outside every route. In the POST route, write return errorResponse(...): the helper sends the answer, and return stops the route there, so the product is not added.


STEP 1 OF 8
    Ctrl + Enter to check

    Shop Error Helper in TypeScript

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