首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从if语句块中退出

从if语句块中退出
EN

Stack Overflow用户
提问于 2020-07-03 10:00:29
回答 2查看 58关注 0票数 0

我正在使用nuxt.js和javascript,并且我正在处理一个表单reCaptcha方法,并且我有一系列的if statements,我需要通过它们才能进入需要的条件块。

我怎样才能在任何阶段都能最好地写出这个代码块,并在每次都不需要写else (重定向错误)的情况下把它们弄错呢?

遍历每个块,如果失败了就把它们扔出去?

代码语言:javascript
复制
        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."
                })
            }
        },
EN

回答 2

Stack Overflow用户

发布于 2020-07-03 10:10:56

Error执行throw操作,并在if之外执行catch (MDN)操作:

代码语言:javascript
复制
try {
  // your if block ... 
  throw new Error('error message');
  // ...
} catch (error) {
   window.$nuxt.error({ 
     statusCode: 500, 
     message: error.message
   });
}

当然,如果您收到相同的错误消息,只需对其进行硬编码,然后简单地使用throw new Error();或任何其他方法即可

票数 0
EN

Stack Overflow用户

发布于 2020-07-03 14:34:46

您可以像下面这样修改代码

代码语言:javascript
复制
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."
                        }) 
            }
        },
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62707399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档