api - 在 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 块有什么作用,我应该如何使用它?
这种设置是否被认为是一种好习惯?任何建议将不胜感激,我仍在学习。
解决方案
可以从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);
}
})
参考:
推荐阅读
- ios - Swift Combine:如何处理事件并继续流
- javascript - 如何使用 MaterializeCSS 创建多个下拉菜单?
- python - 在 Google Colab 的 shell 脚本中连接命令字符串
- linux - 创建符号链接的 Bash 脚本在我的变量中添加字符 ._ 以创建符号链接
- node.js - react native 中可能出现未处理的 Promise Rejection
- javascript - 如何使用 HTML 表单和 Javascript 更新 JSON 文件?
- math - 如何以笛卡尔坐标形式计算内索迪中心点?
- pdf - 在以角度 7 上传之前压缩 PDF
- r - 矩阵中至少有 1 个负值的总列数
- swift - 使用外观代理的全局更改 UINavigationBar 背景不起作用