【问题标题】:Error handling in Express using Axios for API call在 Express 中使用 Axios 进行 API 调用的错误处理
【发布时间】:2020-05-13 02:14:15
【问题描述】:

我正在尝试设置一个基本的快速应用程序来使用 axios 获取一些 API 数据。我想以正确的方式做事,但我对错误处理有点迷茫。理想情况下,如果有错误,我想将它传达给用户,如果 API 调用在路由中,我可以这样做。但是如果它是一个单独的函数,你怎么做呢?

axios 使用异步调用函数:

const getForm = async () => {
    try {
        const config = {
            method: 'get',
            url: 'https://api.something.org/niceform'
            }
        }
        const response = await axios(config)
        return response
    } catch (error) {
        return error.message
    }
}

快速路线:

app.get('/niceform', async (req, res) => {
    try {
        const data = await getForm()
        res.send(data)
    } catch (error) {
        ???
    }
})

如果我理解正确,getForm() 函数将返回响应或错误,然后路由将发送返回的任何内容。但是路由的 catch 块有什么作用,我应该如何使用它呢?

这种设置是否被认为是一种好的做法? 任何建议将不胜感激,我仍在学习。

【问题讨论】:

    标签: api express error-handling async-await axios


    【解决方案1】:

    catch 块可以从getForm 函数中移除。无论如何都会在get 路由中捕获错误。

    const getForm = async () => {
        const config = {
            method: 'get',
            url: 'https://api.something.org/niceform'
        };
    
        const response = await axios(config);
    
        return response;
    }
    

    或者可以在getForm 中捕获错误,以便在该catch 块中执行某些操作并被抛出:

    const getForm = async () => {
        const config = {
            method: 'get',
            url: 'https://api.something.org/niceform'
        };
    
        try {
            const response = await axios(config);
            return response;
        } catch (err) {
            // log the error
            // add extra information to the error
            // else
            // (see the attached answer)
            throw err;
        }
    }
    

    因此,在get路由中的catch块中,可以响应错误:

    app.get('/niceform', async (req, res) => {
        try {
            const data = await getForm();
            res.send(data);
        } catch (error) {
            res.error(error);
        }
    })
    

    参考:

    【讨论】:

    • 完美,非常感谢您的解释,这完全有道理! :)
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多