繁体   English   中英

javascript函数调用时捕获错误

[英]javascript catch errors on function call

Java方法中可以使用关键字throws Exception并在调用方法时抛出所有错误,这减少了try catch的使用

我现在正在学习JavaScript ,但我很难相信JavaScript没有类似的关键字,我们是否想用try-catch块来包围所有内容?

我发现自己正在检查这样的每个变量

if(packet.username && packet.password && packet.id && packet.errors)

然后检查所有这些变量的类型

并使用了很多try catch块,这使得代码非常大而且不清楚

我发现它真的很烦人,有没有办法处理任何错误并在主函数调用中捕获它们?

编辑:因为它有3个答案而所有人都误解了这个问题,对不起,英语不是我的第一语言

我不想知道如何抛出异常,请参考这个java vs javascript示例

我正在编写一个应该处理各种错误的服务器,现在如果发生错误,肯定是客户端正在发送服务器不期望的自己的自定义数据....

在java中,我会做这样的事情

try{
    // I only need to try catch here....
    parsePacket();
}
catch(Exception e){
    e.print();
}

void parsePacket() throws Exception{
    //.....
    // a lot of more possible errors here mainly the ones the server doesn't expect....
    //.....
    anotherFunction();
    //imagine a lot of more functions here that can throw an error
}

void anotherFunction() throws Exception{
    //.....
    // a lot of more posible errors here....
    //.....
}

多么可爱? 只有一个try-catch块,但是在javascript中我发现自己这样做了

JavaScript的

try{

    parsePacket();
}
catch(Exception e){
    e.print();
}

void parsePacket(){
    try{
        //for some reason I have to catch TypeErrors and other ones here too
        //.....
        // a lot of more posible errors
        //.....
        anotherfunction(()=>{
            try{
                //.....
                // a lot of more posible errors here
                //.....
            }
            catch(err){

            }
        })
    }
    catch(err){

    }
}

void anotherFunction(){
    try{
        //.....
        // a lot of more posible errors here
        //.....
    }
    catch(err){

    }
}

它可以很快变得丑陋

JavaScript ,异常处理的工作方式与Java不同。 您需要为每种情况定义您的异常(类型检查)并在大小写匹配时throw该异常,然后该异常将缓存在catch块中。

官方文档中的type check示例:

 function getRectArea(width, height) { if (isNaN(width) || isNaN(height)) { throw "Parameter is not a number!"; } } try { getRectArea(3, 'A'); } catch (e) { console.log(e); // expected output: "Parameter is not a number!" } 

有关throw statement更多详细信息,请在此处查看

我希望这能帮到您。

你可以抛出任何东西而不声明:

function foo() {
  throw {hello: 'world'}
}

我不确定你在做什么,如果你正在使用nodejs并且不限于导入库/包你可以尝试指示在这里你可以指出一组规则来验证你的json。 请参阅参考指示

const { validate } = require('indicative')

const rules = {
  email: 'required|email|unique:users',
  password: 'required|min:6|max:30'
}

const data = {
  email: 'foo@bar.com',
  password: 'weak'
}

validate(data, rules)
  .then(() => {
  })
  .catch((errors) => {
  })

您可以使用一次尝试和一系列捕获整个脚本

try {
    if(packet.username && packet.password && packet.id && packet.errors)
    //all the other code
}
catch(err) {
    document.getElementById("error").innerHTML = err.message;
}
} catch (IOException e) {
    e.printStackTrace();
} catch (NumberFormatException e) {
    e.printStackTrace();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM