PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How to send a custom status and error message if no data found using Node.JS/express and axios?

 November 14, 2022     error-handling, express, node.js, reactjs     No comments   

Issue

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)
    }
}

Solution

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.



Answered By - Heiko Theißen
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing