Marcin
Marcin

Reputation: 600

What is Try-Catch Really Catching

What does Try-Catch really catches? In which scenarios catch will be triggered?

if given request:

try { 
   const response = await axios.get('someURL/api/apiEndpoint')
   ...(do something with response)
} catch(error) {
    console.error(error);
    ...(Do something with error)
}

And Backend Code:

 app.get('/api/apiEndpoint', (req, res, next) => {
     const notLoggedIn = () => {
         return res.status(200).send({
             error: 'Not logged in'
         })
     }
 })

Will that try-catch block catch that there is an error?

Upvotes: 1

Views: 1494

Answers (1)

Abhay Sehgal
Abhay Sehgal

Reputation: 1723

No, it will go in catch block only if response has error status code like 503 (internal server error), 400 (bad request)

In your case you're sending 200 status code, so it will not go inside catch

For more information about status codes check - https://httpstatuses.com/

Upvotes: 1

Related Questions