gpt4 book ai didi

api - 使用Axios进行API调用时Express中的错误处理

转载 作者:行者123 更新时间:2023-12-03 08:43:03 24 4
gpt4 key购买 nike

我正在尝试建立一个基本的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()函数将返回响应或错误,然后路由将发送返回的任何内容。但是,路线的catch块会做什么,我该如何使用呢?

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

最佳答案

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

引用:
  • https://stackoverflow.com/a/42171508/3563737
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw
  • 关于api - 使用Axios进行API调用时Express中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59935617/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com