簡體   English   中英

當 try...catch 塊之一拋出錯誤時,從 function 返回

[英]Return from a function when one of try ... catch block throws an error

我有一個 function ,我在其中提交了一個大表單,它會進行多次 API 調用。 我試圖將它分成更小的函數,因為有一些額外的邏輯取決於 API 響應。 我將每個 API 調用包裝在try... catch中的 function 中,以便我可以更好地控制錯誤。 問題是,每當子 function 之一拋出錯誤時,我需要終止父 function 並且我無法弄清楚這樣做的干凈方法。

所以代碼如下:

const func1 = async() => {
    try {
        // api call + logic
    } catch (error) {
        // show error toast and terminate formSubmit function
    }
}

const func2 = async() => {
    try {
        // api call + logic
    } catch (error) {
        // show error toast and terminate formSubmit function
    }
}

const func3 = async() => {
    try {
        // api call + logic
    } catch (error) {
        // show error toast and terminate formSubmit function
    }
}


const formSubmit = async () => {
    await func1()
    await func2()
    await func3()
}

只需拋出一個新錯誤或重新拋出錯誤,然后在您的表單中添加一個新的處理程序提交 function。

const func1 = async() => {
    try {
        // api call + logic
    } catch (error) {
        // show error toast and terminate formSubmit function
        throw new Error("...");
    }
}

const func2 = async() => {
    try {
        // api call + logic
    } catch (error) {
        // show error toast and terminate formSubmit function
        throw new Error("...");
    }
}

const func3 = async() => {
    try {
        // api call + logic
    } catch (error) {
        // show error toast and terminate formSubmit function
        throw new Error("...");
    }
}


const formSubmit = async () => {
    try {
        await func1()
        await func2()
        await func3()
    } catch(e){
       // do what needs to be done on error
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM