代码之家  ›  专栏  ›  技术社区  ›  Stav Alfi

如何在post/put请求中传输文件并进行错误处理?

  •  0
  • Stav Alfi  · 技术社区  · 5 年前

    这不是关于“重构以下代码的最佳方法是什么”的问题。它是关于“我如何重构下面的代码来控制这两个异常”。


    我有以下代码在PUT请求中流化一个文件。

    import fs from 'fs'
    import got from 'got' // it doesn't really matters if it's `axious` or `got`
    
    async function sendFile(addressToSend: string, filePath: string) {
          const body = fs.createReadStream(filePath)
          body.on('error', () => {
            console.log('we cached the error in block-1')
          })
          try {
            const result = await client.put(addressToSend, {
              body,
            })
          } catch (e) {
            console.log('we cached the error in block-2')
          }
    }
    

    我正试图以这样一种方式重构代码,这样我就有机会在一个地方捕捉所有错误。

    上面的解决方案并没有给我一种方法来测试 stream . 例如,如果我传递一个不存在的文件,函数将同时打印这两个文件 we cached the error in block-1 we cached the error in block-2 但是我没有办法重新抛出第一个错误,或者在测试中使用它。


    注:

    我不确定最好的解决方法是这样做:

    因为当我传递一个不存在的文件路径时 rej 函数将被调用两次,这是非常糟糕的做法。

    function sendFile(addressToSend: string, filePath: string) {
      return new Promise(async (res, rej) => {
        const body = fs.createReadStream(filePath)
        body.on('error', () => {
          console.log('we cached the error in block-1')
          rej('1')
        })
        try {
          const result = await client.put(addressToSend, {
            body,
          })
          res()
        } catch (e) {
          console.log('we cached the error in block-2')
          rej('2')
        }
      })
    }
    
    1 回复  |  直到 5 年前
        1
  •  0
  •   Stav Alfi    5 年前

    function streamFilePut(client: Got, url: string, filePath: string) {
      const body = fs.createReadStream(filePath)
      const streamErrorPromise = new Promise((_, rej) => body.on('error', rej))
    
      const resultPromise = new Promise((res, rej) => {
        return client
          .put(url, {
            body,
          })
          .then(res, rej)
      })
    
      return Promise.race([streamErrorPromise, resultPromise])
    }