Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Express中使用Axios for API调用时的错误处理_Api_Express_Error Handling_Async Await_Axios - Fatal编程技术网

在Express中使用Axios for API调用时的错误处理

在Express中使用Axios for API调用时的错误处理,api,express,error-handling,async-await,axios,Api,Express,Error Handling,Async Await,Axios,我正在尝试设置一个基本的express应用程序,以便使用axios获取一些API数据。我想用正确的方式做事,但我对错误处理有点迷茫。理想情况下,如果出现错误,我希望将其传达给用户,如果API调用在路由中,我可以这样做。但是如果它是一个单独的函数,你怎么做呢 使用异步的axios调用函数: const getForm = async () => { try { const config = { method: 'get',

我正在尝试设置一个基本的express应用程序,以便使用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()
函数将返回响应或错误,然后路由将发送返回的任何内容。但是路线的拦截器是做什么的?我应该如何使用它

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

可以从
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);
    }
})
参考:


太好了,非常感谢您的解释,这完全有道理!:)