Home > Enterprise >  How to catch error messages inside async functions correctly?
How to catch error messages inside async functions correctly?

Time:07-15

app.get('/someFunction', someFunction);

async function someFunction(req, res) {
  try {
    await functionWithError(parameter);
    res.send('success');
  } catch (err) {
    console.log(err); //works
    res.send(err); //does not
  }
}

async function functionWithError(parameter) {
  return (result = await query('SELECT * from table where column = ?', [
    parameter,
  ]));
}

The error in functionWithError is that 'query' is not defined. In try-catch, catch fires correctly but res.send(err) is blank, however console.log(err) works.

CodePudding user response:

Could it be circular structure to JSON error? I suppose as I cannot see your query function.

Can you also try console.log(JSON.stringify(err)) //works ?

If you got error of // ⛔️ TypeError: Converting circular structure to JSON then it is the circular structure issue, that blocks you just "send" as you cannot send a circular object.

For still wanting to send circular object, refer to: https://github.com/WebReflection/flatted#flatted

CodePudding user response:

An error object being thrown here, Should use err.name or err.message.

Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

  • Related