Hypothesis
Hypothesis

Reputation: 1389

How to access try catch error in Javascript through api request?

My nodejs api sends

res.status(401).json({ info: 'task cannot be done' }) 

as an error and I try to catch it on the client side via

try {
      const resp = await axios.get('https://localhost:3000/getinfo')
      console.log('resp!!!', resp)
    } catch (error) {
      console.log('error' , error )
    }

Although on my network tab I can see the message coming in JSON format I am not sure how to extract data from error.

How can I access info which is sent from the server side.

Upvotes: 1

Views: 2844

Answers (3)

Ved
Ved

Reputation: 12093

You can use one of these :
1.

     catch(error){
            const { details } = error;
            const message = details.map(i => i.message).join(',');
            return res.status(400).json({ error: {message:message} })
}
  1.  catch(err){
            let {message} = err;
            return res.status(400).json(
               {
                 error: {
                      message: message,
                 }
            });
      }
    

Upvotes: 0

Yoandry Collazo
Yoandry Collazo

Reputation: 1212

With axios you can handler the error

 const resp = await axios.get('https://localhost:3000/getinfo').catch(err=> 'Do whatever you want with the error');

Upvotes: 1

prince
prince

Reputation: 56

use error.response to get the actual error received from the server on the client

console.log(error.response);

Upvotes: 1

Related Questions