【问题标题】:How to raise error intentionally with express如何使用 express 故意引发错误
【发布时间】:2021-11-12 01:08:54
【问题描述】:

向我的节点服务器发送 axios 请求后,我如何响应“拒绝”Axios 路由/请求并最终出现在客户端代码的“catch()”中?我知道“res.send(data)”或“res.json(data)”将解析为 promise 的“then()”。有什么我可以回应的会拒绝它吗?

axios.post('/edit-item', {_id: id, updateText: editInput.value, author: author}).then((response) => {
    e.target.parentElement.parentElement.children[3].innerHTML = `${response.data}`
}).catch(() => {
    //I want to end up here by responding with something from the server
})

【问题讨论】:

  • 任何 HTTP error 状态码?
  • 你也可以明确你想把哪些HTTP状态码视为错误,axios-http.com/docs/handling_errors
  • 会像这样回应-“res.send(404)”拒绝承诺吗?
  • 我想明确表示我是故意试图抛出一个错误。如您所见,我正在将数据发送到我的快递服务器。如果“作者”字段与某条数据不匹配,我希望承诺拒绝并最终出现在“axios.get()”方法的“catch()”中。

标签: javascript express axios


【解决方案1】:

默认情况下,从您的服务器返回任何不在status >= 200 && status < 300 范围内的http 状态代码将使您进入.catch 块:

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  }

https://axios-http.com/docs/handling_errors

您可以覆盖validateStatus 以定义axios Promise 在哪些情况下为resolved/rejected

【讨论】:

    【解决方案2】:

    您可以在 Node.js 中引发将由内部错误处理程序处理的错误,或者您可以返回您选择的状态代码

    引发错误:

    app.post(req, res, next) {
      throw new Error('Something went wrong')
    

    返回错误信息:

    app.post(req, res, next) {
      res.status(500).send({ error: 'Something failed!' })
    }
    
    

    您可以在此处输入任何错误状态代码,而不是 500

    一旦您返回错误代码,axios 将进入catch 部分

    您可以在此处找到有关错误处理的更多信息:error handling

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      相关资源
      最近更新 更多