javascript捕获函数调用错误

时间:2018-09-13 00:34:39

标签: javascript node.js socket.io

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){

    }
}

它很快就会变得丑陋

4 个答案:

答案 0 :(得分:1)

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 的更多详细信息,请检查here

我希望这会对您有所帮助。

答案 1 :(得分:1)

您可以在不声明的情况下抛出任何东西

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

答案 2 :(得分:1)

我不确定您在做什么,如果您使用的是nodejs,并且不仅限于导入库/包,可以尝试 indicative ,在这里您可以指出要验证的规则集您的json。请参阅参考文献indicative

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) => {
  })

答案 3 :(得分:0)

您可以在整个脚本中使用一个 try 和一系列 catch

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();
}