【问题标题】:In Node.js, what's the correct way to handle an error using async / await?在 Node.js 中,使用 async / await 处理错误的正确方法是什么?
【发布时间】:2018-12-16 02:50:41
【问题描述】:

目前,我有一个功能如下:

export async function getFiles (param: any) {

    try {

        const results = await ... // code to get results from database;
        const files = [];
        for (let i = 0; i < results.length; i++) {

              files.push(results[i]);
        }
        return files;
    }
    catch (error) {
        console.log(error);
    }

}

另外,我使用库函数如下:

    const files = await lib.getFilesAsync(param);
    for (const file of files) {
        // process file here
    }

如何正确地向该代码添加错误处理?

我尝试在 catch 中返回错误:

catch (error) {
    console.log(error);
    return new Error("getFiles error");
}

然后我在编译时收到以下错误:

Type 'Error' must have a '[Symbol.iterator]()' method that returns an iterator. (2488)

【问题讨论】:

    标签: node.js error-handling async-await


    【解决方案1】:

    async 函数返回一个承诺。因此,在 async 函数中,您必须做出设计决定,即您是否希望错误返回被拒绝的承诺或某种可以测试的特定错误。无论哪种情况,async 函数的调用者都需要进行错误检查。这里有两种可能的实现方式。走哪条路真的是您的设计选择。

    它有点类似于一个同步函数,它可以返回像null 这样的标记值,当它有错误时必须由调用者进行测试,或者它可以抛出一个异常,调用者可以使用 try/ 捕获该异常。抓住。

    调用者使用.catch()try/catch

    export async function getFiles (param: any) {
        // if any await operation here rejects, the promise returned
        // from getFiles() will reject and the caller can .catch() the error
        const results = await ... // code to get results from database;
        const files = [];
        for (let i = 0; i < results.length; i++) {
             files.push(results[i]);
        }
        return files;
    }
    
    // usage
    getFiles(...).then(files => {
        console.log(files);
    }).catch(err => {
        console.log(err);
    })
    
    // or, you could use it this way
    try {
        let files = await getFiles(...);
        console.log(files);
    } catch(e) {
        console.log(e);
    }
    

    调用者检查已解决的承诺是否有错误

    export async function getFiles (param: any) {
    
        try {
            const results = await ... // code to get results from database;
            const files = [];
            for (let i = 0; i < results.length; i++) {
    
                  files.push(results[i]);
            }
            return files;
        }
        catch (error) {
            console.log(error);
            return new Error("getFiles error");
        }
    }
    
    // usage:
    getFiles(...).then(files => {
        console.log(files);
        if (files instanceof Error) {
            // error
        } else {
            // process files array here
        }
    });
    
    // or, you could use it this way
    let files = await getFiles(...);
    console.log(files);
    if (files instanceof Error) {
        // error
    } else {
        // process files array here
    }
    

    就个人而言,我更喜欢使用被拒绝的 Promise,因为如果您让 Promise 为您管理错误传播,那么排序或链接异步操作会容易得多。

    【讨论】:

    • 嗨 jfriend 使用 async await 我需要安装任何模块吗...我可以在我的 react 项目前端使用它吗?
    • @AnthonyWinzlet - 在 node.js 中,您不再需要任何模块。 async/await 需要适当的 ES7 支持。在 node.js 中是 v7.6 之后的任何版本。对于浏览器中的前端支持,所有流行浏览器(不是 IE)的最新版本都支持它,但是您必须更具体地了解您的浏览器要求,因为不是每个人都在运行最新版本的浏览器所以前端比较复杂。你可以使用 BabelJS 之类的东西将你的前端代码转换为 ES5,这样它就可以在旧版浏览器中运行。
    猜你喜欢
    • 2018-04-13
    • 2018-06-10
    • 2020-12-02
    • 2019-04-21
    • 2014-09-20
    • 2021-12-31
    • 1970-01-01
    • 2020-06-02
    • 2021-11-15
    相关资源
    最近更新 更多