簡體   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