2

In my Node Express JS web app, I have the following function chain where the subsequent api function tries to call the service function and catch the error thrown from the service function.

In FWBDataExtracService.js

const FWBDataExtracService = {
    getFWBData: async () => {
        ... ...
        // Check if .tabledata exists; If not, throw an error to be caught in the calling function.
        if ($('.tabledata1').length == 0) {
            console.error("DOM element .tabledata not found on the page.");
            throw new Error("DOM element .tabledata not found on the page.");
        }
        ... ...
    }
}

In api.js, the router function is trying to call the FWBDataExtracService.getFWBData function and then catching the error.

const FWBDataExtracService = require('../services/FWBDataExtracService')
router.get('/GetDataFromFWB', async (req, res, next) => {
    try {
        .... ....
        // ### THIS WILL FAIL AND AN ERROR WILL BE THROWN
        const FWBJson = await FWBDataExtracService.getFWBData();
        .... ....
    } catch(err) {
        // ### ERR IS ALWAYS EMPTY
        console.log("*", JSON.stringify(err));
        return res.send({'Error': JSON.stringify(err)});
    }
})

As the error was mimicked I was expecting the error to be caught and print out the err message. But err was always empty.

1
  • 1
    Try to show what err.stack displays? Commented Jun 9, 2021 at 0:08

1 Answer 1

4

The precise location of error properties is not specified. In some environments, it's on the error object itself - in some, it's on the prototype, or is a getter, or something like that.

JSON.stringify will only iterate over enumerable own properties. In Chrome, the .message property is not enumerable, so it won't be included when stringified:

const e = new Error('foo');
console.log(Object.getOwnPropertyDescriptor(e, 'message'));

Best approach here would be to explicitly extract the properties you want instead of using JSON.stringify. Change

console.log("*", JSON.stringify(err));

to something like

const { message } = err;
console.log("*", message);
 return res.send({ Error: message });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.