查找请求错误

Finding errors with request

我有一个 post 到端点的脚本,就像使用 node.js 请求模块 https://github.com/request/request

const options = {
  url: path,
  formData: {
    name: name,
    bundle: fs.createReadStream(path)
  }
}


request.post(options, function(err, httpResponse, body) {
 if (err) {
  console.log('Error!')
 } else {
  console.log('Success!')
 }
})

我正试图捕捉 post 失败且不起作用的时间。我尝试故意上传一些东西并得到 400 回复,但它仍然成功返回。有没有更合适的方法来处理请求模块的错误捕获?

请求库不会填充请求回调的 error 参数,除非传输中存在实际错误或其他运行时问题。在 GitHub 上查看此问题:404 error does not cause callback to fail #2196

Currently request does not handle the HTTP errors. You can wrap the callback and add your own logic there.

要检查 HTTP 错误,请检查 response 参数的 statusCode 属性:

request.post(options, function (err, httpResponse, body) {
    if (err || httpResponse.statusCode >= 400) {
        return console.error("Something went wrong");
    }
    console.log('Success!')
});