Kevin Powell - CommunityKP-C
Kevin Powell - Community2mo ago
15 replies
Faker

Try catch block best practices

Hello, consider this route code:

import express from "express";
import { ObjectId } from "mongodb";
import { db } from "../server.js";

const orderRouter = express.Router();

// Add order to card
orderRouter.post("", async (req, res) => {
  // get request value inside req.body
  const id = req.body.id;

  // Retrieve lesson details
  const product = await db
    .collection("products")
    .find({ _id: new ObjectId(id) })
    .toArray();

  const [order] = product;

  if (order.spaces > 0) {
    let [newOrder] = product;

    await db.collection("orders").insertOne({
      src: newOrder.src,
      subject: newOrder.subject,
      location: newOrder.location,
      price: newOrder.price,
    });

    newOrder = {
      src: newOrder.src,
      subject: newOrder.subject,
      location: newOrder.location,
      price: newOrder.price,
    };

    res
      .status(200)
      .json({ message: "Order successfully created !", order: newOrder });
  } else {
    res
      .status(500)
      .json({ message: "Number of spaces depleted, cannot add to cart !" });
  }
});

export { orderRouter };

It works fine but I have the bad habit of not writing "robust" code, like using try catch when it comes to network request like fetching data from a database.

I was wondering if anyone can share their experience about when should I use try catch block and how can I make it become natural to me, like when I code, I don't really think about it like in the code above, I didn't really bother about it :c.
Was this page helpful?