'How to access error message in the front end sent by the server?

In my node backend, this is how I send the error message to the front end:

catch (err) {
    res.status(500).json("UNEXPECTED ERROR. Please try again later.");
  }

How do I access the error message in the backend? Is this correct?

catch (err) {
  err.response.data;
}


Solution 1:[1]

You can access the error message like: error.message

I have tried in typescript this worked for me.

try {
    throw new Error("UNEXPECTED ERROR. Please try again later.");
  } catch (error: any) {
    console.log(error!.message);
    return res.status(400).send(error!.message);
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pranu Pranav