什么是真正的Try-Catch捕获

时间:2019-02-03 11:28:31

标签: javascript try-catch

Try-Catch真正抓住了什么?在哪种情况下会触发捕获?

如果有要求:

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

和后端代码:

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

try-catch块会捕获到错误吗?

1 个答案:

答案 0 :(得分:1)

否,仅当响应具有错误状态码(例如503(内部服务器错误),400(错误请求))时,它才会进入catch块

在您的情况下,您将发送200个状态代码,因此它不会进入catch状态

有关状态码的更多信息,请检查-https://httpstatuses.com/