javascript - 处理与用户(操作)相关的错误的适当方法是什么?
问题描述
我正在挠头,试图找出处理特定用户操作错误的最佳方法。我使用 Express 作为我的 Web 服务器,尽管它可以正常工作,但在大多数情况下,我会收到不太有用的通用错误消息。例如,在下面的代码中,我Request failed with status code 400
在客户端收到 try 块中前两个条件/异常的错误消息。
在以下示例中如何处理?
Express 服务器端控制器
async function voteInPoll (req, res) {
const { category, pollId } = req.params;
const { name, choiceId, voterId } = req.body;
try {
const poll = await Poll.findById(pollId);
// Check if user has already voted in poll
const hasVoted = poll.votedBy.some(voter => voter.equals(voterId));
if (!voterId) { // Check if user is authenticated
res
.sendStatus(400)
.json({ message: 'Sorry, you must be logged in to vote' });
} else if (voterId && hasVoted) {
res
.sendStatus(400)
.json({ message: 'Sorry, you can only vote once' });
} else {
const choice = await poll.choices.id(choiceId);
const votedChoice = { name, votes: choice.votes + 1 };
await choice.set(votedChoice);
await poll.votedBy.push(voterId);
poll.save();
res
.sendStatus(200)
.json({
message: 'Thank you for voting. Find other polls at: ',
poll,
});
}
} catch (error) {
throw new Error(error);
}
}
反应/Redux 动作
export const voteInPoll = (category, pollId, votedItem, voterId) => async dispatch => {
try {
const response = await axios.post(
`http://localhost:3050/polls/${category}/${pollId}/vote`,
{
...votedItem,
voterId,
}
);
dispatch({ type: store.polls.VOTE_SUCCESS, payload: response.data.poll });
} catch (error) {
console.log(error);
dispatch({ type: store.polls.VOTE_FAILURE, payload: error.message });
}
};
编辑
解决方案
由于此处res.sendStatus(statusCode)
的文档中定义的以下内容,您不应该使用:
将响应 HTTP 状态代码设置为 statusCode 并将其字符串表示形式作为响应正文发送。
上面的关键是:
并将其字符串表示形式作为响应正文发送。
这样做:不会res.sendStatus(400).json({ message: 'Oops 400!'})
为您提供您所期望的 JSON 响应,而只是显示:
Bad Request
这是 HTTP 状态代码的字符串表示:https ://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_errors400
你需要做的就是用这样的方式替换你的所有res.sendStatus(..).json(..)
内容res.status(...).json(...)
:
if (!voterId) { // Check if user is authenticated
res
.status(400)
.json({ message: 'Sorry, you must be logged in to vote' });
} else if (voterId && hasVoted) {
res
.status(400)
.json({ message: 'Sorry, you can only vote once' });
} else {
// ...
}
等等。
推荐阅读
- ruby-on-rails - 从 S3 的视图中拯救 403 个禁止的图像
- lua - Lua“busted.runner”必须在每个文件上
- java - 访问 Crypto API 需要哪些权限?
- java - Java Regex - 如何替换模式以开头和结尾
- java - 使用 Talend 从包含多结构文件的目录中提取标头
- sql - 找不到 ORA-00907:缺少右括号
- python - Pytest:根据 config.ini 中指定的次数运行所有测试
- node.js - nodejs rest url中的模式匹配
- python - 从 sklearn 尝试“LeaveOneGroupOut”时收到 python 异常
- spotify-scio - 为什么在排空流式管道时会收到很多 None.get 异常?