Not able to send error caught into a response

Issue

I am making a POST request where the body is of type form-data.

The body contains the following data:

enter image description here

I have a middleware that is trying to parse data(stringified JSON) field in the body to JS object.

/**
 * - Convert req.body.data to JSON and will attach it to body
 */
const customParser = (req, res, next) => {
  try {
    req.body = JSON.parse(req.body.data);
    next();
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: error });
  }
};

/**
 * - Route to request a community
 */
router.post(
  "/v1/user/community/request",
  userAuthorization,
  multer.single("image"),
  customParser,
  requestCommunity
);

The issue I am getting is when JSON.parse() is throwing error. I can log the error in the console but when I am sending the same error back into response I am getting an empty object.

Response:
enter image description here

Console:
enter image description here

I need help from you guys to figure out what mistake I am doing.

Minimal, Reproducible Example:

const express = require("express");

const server = express();

const customParser = (req, res, next) => {
  try {
    const testData = '{"name: "John"}';
    req.body = JSON.parse(testData);
    next();
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: error });
  }
};

server.get("/", customParser, (req, res) => {
  res.json({parsedData: req.body});
});

server.listen(3000);

Solution

Error instances can’t be JSON-stringified because they don’t have enumerable properties.

You can use this to return the error message in the response.

res.status(500).json({ error : error.message });

And/or error.stack to return the error message and the entire stack trace.

Answered By – robertklep

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published