简体   繁体   English

配管前捕获超级代理请求错误

[英]Catch superagent request error before piping

I'm trying to pipe a file from service A trough service B into my Postman cliente. 我正在尝试通过服务A到服务B的文件将文件传输到我的Postman客户程序中。 Service A builds an delivers a CSV file, and service B (nodejs) has to pipe into my client. 服务A构建了一个交付CSV文件的服务,服务B(nodejs)必须通过管道传输到我的客户端。

After researching a lot I have managed to successfully pipe the files into service B and then into Postman. 经过大量研究后,我成功地将文件通过管道传输到服务B中,然后再传输到Postman中。 Now I want to handle the ugly cases: what if the request token is invalid? 现在,我要处理一些丑陋的情况:如果请求令牌无效,该怎么办? What if I can't find the file? 如果找不到文件怎么办?

As of this moment, I have found zero documentation or examples on how successfully handle errors while piping a request using superagent. 到目前为止,我发现了零文档或示例,这些示例或示例说明了在使用超级代理传递请求时如何成功处理错误。

This is what I have so far 这就是我到目前为止

router.post("/csv", (req, res) => {
  download_csv(req.get("Authorization"), req.body.ids)
  .then((response) => {
    res.sendFile(path.resolve(response));
  })
  .catch((err) => {
    res.status(error.status).json(error.response.body);
  })   
});

function download_csv(token, ids) {
  const stream = fs.createWriteStream("filters.csv")
  let request = agent
    .post(`${profiles}/api/documents/csv`)
    .set("authorization", token)
    .send({
      ids: ids,
      action: DOWNLOAD_CSV_PROFILES
    })

  request.on("response", res => {
    // Maybe I can use abort to handle this thing, but can't figure out how!
    // if (res.status !== 200) request.abort()
    console.log(res.status)
  })

  request.on("abort", () => {
    console.log("aborted")
    return new Promise((resolve, reject) => {
      resolve("request aborted")
    })
  })

  request.pipe(stream)
  return streamToPromise(stream);
}

function streamToPromise(stream) {
  return new Promise((resolve, reject) => {
    stream.on("error", (err) => {
      console.log("error in error")
    })
    stream.on("finish", () => {
      console.log("File saved")
      resolve(stream.path);
    });
  });
}

This code handles the creation of the files correctly . 此代码正确处理了文件的创建。 When I fake the token or misspell the Authorization header, I get a correct 401 response, but a file gets written anyway with its contents being the authentication error. 当我伪造令牌或拼写错误的Authorization标头时,我会收到正确的401响应,但是无论如何都会写入文件,其内容为身份验证错误。

Can anyway give me a hint on how to: 无论如何可以给我一个提示:

  • actually catch and manage the request when fails 失败时实际捕获并管理请求
  • in such case, how to escape the piping by going back to the express context and just returning a failed express request? 在这种情况下,如何通过返回快递上下文并仅返回失败的快递请求来逃避管道运输?

Many thanks! 非常感谢!

If I understand you correctly, simply create the fs write stream in on('response') and make a small fix on the resultion. 如果我对您的理解正确,只需在on('response')中创建fs写流,并对结果进行小幅修复。

function download_csv(token, ids) {
    return new Promise((resolve, reject) => {
      let request = agent
        .post(`${profiles}/api/documents/csv`)
        .set("authorization", token)
        .send({
          ids: ids,
          action: DOWNLOAD_CSV_PROFILES
        })

      request.on("response", res => {
        // Maybe I can use abort to handle this thing, but can't figure out how!
        if (res.status === 200) {
            res
              .on("end", resolve)
              .pipe(fs.createWriteStream("filters.csv"));
        } else {
          reject();
        }
      })

      request.on("abort", reject);

  });
}

I'm not sure what is the "request" you're using - but assuming it's actually the request npm module that will help. 我不确定您使用的“请求”是什么-但假设实际上是请求npm模块会有所帮助。

Ideally, upload the file to a temporary directory and move it when the promise is resolved, delete on rejected. 理想情况下,将文件上传到临时目录,并在解决诺言后将其移动,在被拒绝时删除。 This way you'll solve the issue of partial downloads. 这样,您将解决部分下载的问题。

If you want to make any on-the-fly transforms, check out my " scramjet ". 如果您想即时进行转换,请查看我的“ 超燃冲压发动机 ”。 It'll make everything easier with promises. 有了诺言,一切都会变得更加轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM