我目前正在尝试围绕第三方 API 构建一个 API,但是在我的 Express 路由中,我似乎无法让当前脚本停止执行,这是我的代码:
app.get('/submit/:imei', async function (req, res) {
//configure
res.setHeader('Content-Type', 'application/json');
MyUserAgent = UserAgent.getRandom();
axios.defaults.withCredentials = true;
const model_info = await getModelInfo(req.params.imei).catch(function (error) {
if(error.response && error.response.status === 406) {
return res.send(JSON.stringify({
'success': false,
'reason': 'exceeded_daily_attempts'
}));
}
});
console.log('This still gets called even after 406 error!');
});
如果初始请求返回406错误,如何阻止脚本执行?
如果你不希望代码在捕获错误后执行,那么你应该这样做:
app.get('/submit/:imei', async function (req, res) {
//configure
res.setHeader('Content-Type', 'application/json');
MyUserAgent = UserAgent.getRandom();
axios.defaults.withCredentials = true;
try {
const model_info = await getModelInfo(req.params.imei);
console.log('This will not get called if there is an error in getModelInfo');
res.send({ success: true });
} catch(error) {
if(error.response && error.response.status === 406) {
return res.send({
'success': false,
'reason': 'exceeded_daily_attempts'
});
}
}
});
或者,您可以在getModelInfo
调用后使用then
,并且只有在getModelInfo
未拒绝时才调用该代码。
它也应该有一个成功块。
app.get('/submit/:imei', async function (req, res) {
//configure
res.setHeader('Content-Type', 'application/json');
MyUserAgent = UserAgent.getRandom();
axios.defaults.withCredentials = true;
const model_info = await getModelInfo(req.params.imei)
.then(function (response) {
return res.send(JSON.stringify({
'success': true,
'res': response
}));
})
.catch(function (error) {
if (error.response && error.response.status === 406) {
return res.send(JSON.stringify({
'success': false,
'reason': 'exceeded_daily_attempts'
}));
}
});
//it will console log
console.log('This still gets called even after 406 error!');
});