Home > Enterprise >  How to send a custom status and error message if no data found using Node.JS/express and axios?
How to send a custom status and error message if no data found using Node.JS/express and axios?

Time:11-08

If no user is found (it's just an example to understand error handling), I want to send a custom message such as

res.status(404).send('no user');

my client never receives that and instead I get:

[AxiosError: Request failed with status code 404]

What am I doing wrong? I cannot find any other solution and have been researching for a while now. Also wonder how I could send a custom status (if no data found it's 404 but what if I want to send 200)? node express

router.get('/getuser', async (req, res) => {
    try {
        const user = await User.findOne({_id: req.user._id});
        if (!user) {
            res.status(404).send('no user');
        } else {
            res.status(200).send(user)
        }

    } catch(error) {
        res.status(500).send(error)
    }
});

frontend

const trycatch = async () => {
    try {
        const response = await axios.get(example.com/trycatch)
        return response.data;
    } catch (error) {
        console.log(error)
    }
}

CodePudding user response:

Responses with a status code of 400 or more are treated as errors by axios. As a consumer, you can only react to that in the catch (error) clause, for example:

catch (error) {
  switch (error.response.status) {
    case 404: return "no user"; break;
    default: return error.response.data;
  }
}

But you can influence which statuses cause errors with the validateStatus option of the axios request.

Summary: Either you distribute your code between the try and the catch block, where the try block code handles successes (status < 400) and the catch block handles errors (status ≥ 400). Or you use validateStatus to change what counts as a success and what counts as an error.

  • Related