sashankshukla / splash

2 stars 0 forks source link

Update express backend with proper try catch #82

Closed sashankshukla closed 1 year ago

sashankshukla commented 1 year ago

Currently, when there is some sort of error (server or validation) we use throw new Error with a status code. This is kind of problematic since it breaks the server every time. We need a try-catch in each of our API controllers to use our errorMiddleware which deals with any errors we throw as well as server or mongoose errors. This will prevent the server from breaking.

An example refactor would look like this: Before

  req.body.address = JSON.parse(req.body.address);
  req.body.details = JSON.parse(req.body.details);
  if (!req.body.name || !req.body.address || !req.body.price || !req.user.email) {
    res.status(400);
    throw new Error('Please specify a name, address, price, and email');
  }

  const images = req.files.map((file) => file.location); // Retrieve the file paths of all the uploaded images

  const listing = await Listing.create({
    ...req.body,
    images,
    createdBy: req.user.email,
  });
  res.status(200).json(listing);
}; 

After

const addListing = async (req, res, next) => {
  try {
    req.body.address = JSON.parse(req.body.address);
    req.body.details = JSON.parse(req.body.details);

    if (!req.body.name || !req.body.address || !req.body.price || !req.user.email) {
      throw new Error('Please specify a name, address, price, and email');
    }

    const images = req.files.map((file) => file.location); // Retrieve the file paths of all the uploaded images

    const listing = await Listing.create({
      ...req.body,
      images,
      createdBy: req.user.email,
    });

    res.status(200).json(listing);

  } catch (error) {
    next(error); // Pass the error to the error handling middleware
  }
};
sashankshukla commented 1 year ago

we already specify app.use(errorHandler) in app.js so we just need all routes to use this next() and then the thunks should be able to handle errors and server wont crash

sashankshukla commented 1 year ago

Check out errorMiddleware for more details about what its doing

sashankshukla commented 1 year ago

Traversy makes use of express async handler , https://github.com/bradtraversy/mern-tutorial/tree/main/backend/controllers. Feel free to try this way instead too.