javascript捕获函数调用错误

cen*_*ond 5 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....
    //.....
}
Run Code Online (Sandbox Code Playgroud)

多么可爱?只是一个 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){

    }
}
Run Code Online (Sandbox Code Playgroud)

它很快就会变得丑陋

小智 1

我不确定你在做什么,如果你正在使用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) => {
  })
Run Code Online (Sandbox Code Playgroud)