【发布时间】:2021-07-27 03:34:21
【问题描述】:
我正在构建我的第一个全栈应用程序,我在后端处理错误时遇到问题,我也不知道如何在前端接收此错误消息。
这是我的应用程序的工作方式: (我正在使用 nodejs、express.js、mongodb 和 react)
// 1. I got a form where user provide some data.
// 2. Redux action creator is sending this data to my API.
// 3. Basing on this data, my API is fetching other API for some information.
// 4. And the response is pushed to my data base, and then send back to my reducer, and it's in my store.
事情是,在我将响应推送到我的数据库之前,我想检查这个项目是否存在于我在后端获取的 API 中,如果不存在,那么我想接收这种消息,并显示就在表单下方给我的用户。
这是我在前端的动作创建者:
export const addTransaction = (transaction) => async (dispatch) => {
try {
const { data } = await api.addTransaction(transaction);
dispatch({
type: ADD_TRANSACTION,
payload: data
});
} catch (error) {
console.log(error.message);
};
};
这是我的后端控制器:
export const addTransaction = async (req, res) => {
const transaction= req.body
const myUpdatedTransaction = {
...transaction,
someOther: "fields"
};
const requestOptions = {/*GET, url, api_key, etc. */},
// here is where I'm trying to handle this case
await request(requestOptions).then( async (resolve) => {
if(resolve) {
const newTransaction = new TransactionItem(myUpdatedTransaction)
await newTransaction.save();
res.status(201).json(newTransaction);
return;
}
}, (err) => {
/******** And here where I don't know how to deal with this *******/
console.log('error ----->');
if(err) {
res.status(409).json({ message: 'Check if the ticker is correct.'});
console.log('409');
return;
}
});
};
如果有人可以分享一些链接,我可以了解有关错误处理的更多信息,我将不胜感激。
【问题讨论】:
标签: javascript node.js express error-handling