Relocate 4xx/5xx exception in downloadFile (#17332) [backport:1.2]
Move 4xx/5xx exception to before disk i/o. As it stands an empty file is created on http error 4xx/5xx.
This commit is contained in:
parent
23393b8478
commit
3d198fdcc2
1 changed files with 6 additions and 6 deletions
|
|
@ -1219,6 +1219,9 @@ proc downloadFile*(client: HttpClient, url: Uri | string, filename: string) =
|
||||||
defer:
|
defer:
|
||||||
client.getBody = true
|
client.getBody = true
|
||||||
let resp = client.get(url)
|
let resp = client.get(url)
|
||||||
|
|
||||||
|
if resp.code.is4xx or resp.code.is5xx:
|
||||||
|
raise newException(HttpRequestError, resp.status)
|
||||||
|
|
||||||
client.bodyStream = newFileStream(filename, fmWrite)
|
client.bodyStream = newFileStream(filename, fmWrite)
|
||||||
if client.bodyStream.isNil:
|
if client.bodyStream.isNil:
|
||||||
|
|
@ -1226,14 +1229,14 @@ proc downloadFile*(client: HttpClient, url: Uri | string, filename: string) =
|
||||||
parseBody(client, resp.headers, resp.version)
|
parseBody(client, resp.headers, resp.version)
|
||||||
client.bodyStream.close()
|
client.bodyStream.close()
|
||||||
|
|
||||||
if resp.code.is4xx or resp.code.is5xx:
|
|
||||||
raise newException(HttpRequestError, resp.status)
|
|
||||||
|
|
||||||
proc downloadFileEx(client: AsyncHttpClient,
|
proc downloadFileEx(client: AsyncHttpClient,
|
||||||
url: Uri | string, filename: string): Future[void] {.async.} =
|
url: Uri | string, filename: string): Future[void] {.async.} =
|
||||||
## Downloads `url` and saves it to `filename`.
|
## Downloads `url` and saves it to `filename`.
|
||||||
client.getBody = false
|
client.getBody = false
|
||||||
let resp = await client.get(url)
|
let resp = await client.get(url)
|
||||||
|
|
||||||
|
if resp.code.is4xx or resp.code.is5xx:
|
||||||
|
raise newException(HttpRequestError, resp.status)
|
||||||
|
|
||||||
client.bodyStream = newFutureStream[string]("downloadFile")
|
client.bodyStream = newFutureStream[string]("downloadFile")
|
||||||
var file = openAsync(filename, fmWrite)
|
var file = openAsync(filename, fmWrite)
|
||||||
|
|
@ -1248,9 +1251,6 @@ proc downloadFileEx(client: AsyncHttpClient,
|
||||||
# `bodyStream` has been written to the file.
|
# `bodyStream` has been written to the file.
|
||||||
await file.writeFromStream(client.bodyStream)
|
await file.writeFromStream(client.bodyStream)
|
||||||
|
|
||||||
if resp.code.is4xx or resp.code.is5xx:
|
|
||||||
raise newException(HttpRequestError, resp.status)
|
|
||||||
|
|
||||||
proc downloadFile*(client: AsyncHttpClient, url: Uri | string,
|
proc downloadFile*(client: AsyncHttpClient, url: Uri | string,
|
||||||
filename: string): Future[void] =
|
filename: string): Future[void] =
|
||||||
result = newFuture[void]("downloadFile")
|
result = newFuture[void]("downloadFile")
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue