首页 > 解决方案 > 在 Express 中使用 Axios 进行 API 调用的错误处理

问题描述

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

使用 async 的 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 块有什么作用,我应该如何使用它?

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

标签: apiexpresserror-handlingasync-awaitaxios

解决方案


可以从getForm函数中删除 catch 块。无论如何都会在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);
    }
})

参考:


推荐阅读