首页 > 解决方案 > 处理与用户(操作)相关的错误的适当方法是什么?

问题描述

我正在挠头,试图找出处理特定用户操作错误的最佳方法。我使用 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 });
  }
};

编辑

我发现相当奇怪的是,我收到了预期的错误响应,如下图所示,在 Chrome 开发者工具的网络选项卡下。 在此处输入图像描述

标签: javascriptnode.jsexpressredux

解决方案


由于此处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 {
  // ...
}

等等。


推荐阅读