网站搜索

node.js - 在函数调用中捕获 JavaScript 错误


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

我现在正在学习JavaScript,但我很难相信JavaScript中没有类似的关键字,我们是不是必须用try-catch块包围所有东西?

我发现自己像这样检查每一个变量

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

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

并且使用大量的 try catch 块,这使代码非常庞大且不清晰

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

编辑:因为已经有三个回答了,而且它们都误解了问题,对此表示抱歉,英语不是我的母语

我不想知道如何抛出异常,看看这个 Java 和 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){

    }
}

而且情况可能很快变得糟糕

答案#1

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

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

答案#2

在JavaScript中,异常处理的工作方式与Java略有不同。你需要为每种情况(类型检查)定义你的异常,并在情况匹配时throw该异常,然后该异常将会在catch块中被捕获。

官方文档中 类型检查 的示例:

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 语句 的更多详细信息,请查看此处。

我希望这能帮到你。