我正在使用nuxt.js和javascript,并且我正在处理一个表单reCaptcha方法,并且我有一系列的if statements,我需要通过它们才能进入需要的条件块。
我怎样才能在任何阶段都能最好地写出这个代码块,并在每次都不需要写else (重定向错误)的情况下把它们弄错呢?
遍历每个块,如果失败了就把它们扔出去?
if(sauhp.length < 1){
//sauhp is empty and not a bot - proceed
const token = await this.$recaptcha(formType);
//Send the token to validate
let verifyReCaptcha = await axios.get('/api/recaptcha/api/siteverify?secret='+secret+'&response='+token);
let reCaptchaResponse = verifyReCaptcha.data;
//Validate the action
if(reCaptchaResponse.action === formType){
//Process the form
if(reCaptchaResponse.score > 1){
console.log('yes great go ahead')
}else{
window.$nuxt.error({
statusCode: 500,
message: "We've detected a problem in the form submission. Call us, we're here to help."
})
}
}
}else{
window.$nuxt.error({
statusCode: 500,
message: "We've detected a problem in the form submission. Call us, we're here to help."
})
}
},发布于 2020-07-03 10:10:56
对Error执行throw操作,并在if之外执行catch (MDN)操作:
try {
// your if block ...
throw new Error('error message');
// ...
} catch (error) {
window.$nuxt.error({
statusCode: 500,
message: error.message
});
}当然,如果您收到相同的错误消息,只需对其进行硬编码,然后简单地使用throw new Error();或任何其他方法即可
发布于 2020-07-03 14:34:46
您可以像下面这样修改代码
if(sauhp.length < 1){
//sauhp is empty and not a bot - proceed
const token = await this.$recaptcha(formType);
//Send the token to validate
let verifyReCaptcha = await axios.get('/api/recaptcha/api/siteverify?secret='+secret+'&response='+token);
let reCaptchaResponse = verifyReCaptcha.data;
//Validate the action
if(reCaptchaResponse.action === formType && reCaptchaResponse.score > 1){
console.log('yes great go ahead')
return true;
}
}
window.$nuxt.error({
statusCode: 500,
message: "We've detected a problem in the form submission. Call us, we're here to help."
})
}
},https://stackoverflow.com/questions/62707399
复制相似问题