【发布时间】:2020-02-02 23:59:07
【问题描述】:
这不是关于“重构以下代码的最佳方法是什么”的问题。它是关于“我如何重构以下代码以控制这两个异常”。
我有以下代码在 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')
}
})
}
【问题讨论】:
标签: node.js error-handling node-streams