From 1119e6e1f98a0952b8ce193dde9200ea102bdfe4 Mon Sep 17 00:00:00 2001 From: unitwk Date: Sat, 29 Oct 2022 16:22:08 +0800 Subject: [PATCH] Feat: add download file try catch --- src/service/download.ts | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/service/download.ts b/src/service/download.ts index c0ded77..f0e3786 100644 --- a/src/service/download.ts +++ b/src/service/download.ts @@ -9,20 +9,21 @@ import logger from "./log"; export function downloadFileToLocalFile(url: string, localFilePath: string): Promise { logger.info(`Download File: ${url} --> ${path.normalize(localFilePath)}`); return new Promise(async (resolve, reject) => { - const writeStream = fs.createWriteStream(path.normalize(localFilePath)); - const response = await axios({ - url, - responseType: "stream" - }); - if (response.status > 299 || response.status < 200) { - reject(new Error(`Download File: Target File response code is ${response.status} NOT 2XX.`)); + try { + const writeStream = fs.createWriteStream(path.normalize(localFilePath)); + const response = await axios({ + url, + responseType: "stream" + }); + pipeline(response.data, writeStream, (err) => { + if (err) { + reject(err); + } else { + resolve(true); + } + }); + } catch (error) { + reject(error); } - pipeline(response.data, writeStream, (err) => { - if (err) { - reject(err); - } else { - resolve(true); - } - }); }); }