Skip to content

Commit c1b1b8a

Browse files
fix: handle file deletion on download failure and improve error handling
1 parent 18a417f commit c1b1b8a

2 files changed

Lines changed: 25 additions & 21 deletions

File tree

android/src/main/java/com/mendix/mendixnative/react/download/DownloadHelper.kt

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -43,23 +43,31 @@ fun downloadFile(
4343
outputFile.parentFile?.mkdirs()
4444
outputFile.createNewFile()
4545

46-
client.newCall(Request.Builder().url(url).get().build()).enqueue(object : Callback {
47-
override fun onFailure(call: Call, e: IOException) = onFailure(e)
48-
49-
override fun onResponse(call: Call, response: Response) {
50-
try {
51-
DownloadResponseHandler(
52-
response,
53-
expectedMimeType,
54-
outputFile,
55-
progressCallback,
56-
).handle()
57-
onSuccess()
58-
} catch (e: Exception) {
46+
try {
47+
client.newCall(Request.Builder().url(url).get().build()).enqueue(object : Callback {
48+
override fun onFailure(call: Call, e: IOException) {
49+
outputFile.delete()
5950
onFailure(e)
6051
}
61-
}
62-
})
52+
53+
override fun onResponse(call: Call, response: Response) {
54+
try {
55+
DownloadResponseHandler(
56+
response,
57+
expectedMimeType,
58+
outputFile,
59+
progressCallback,
60+
).handle()
61+
onSuccess()
62+
} catch (e: Exception) {
63+
onFailure(e)
64+
}
65+
}
66+
})
67+
} catch (e: Exception) {
68+
outputFile.delete()
69+
throw e
70+
}
6371
}
6472

6573

example/__tests__/download-handler.harness.ts

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ describe('NativeDownloadHandler', () => {
2121
};
2222

2323
await expect(
24-
await NativeDownloadHandler.download(
24+
NativeDownloadHandler.download(
2525
'://definitely-invalid-url',
2626
downloadPath,
2727
config
@@ -39,11 +39,7 @@ describe('NativeDownloadHandler', () => {
3939
const originalConfig = { ...config };
4040

4141
await expect(
42-
await NativeDownloadHandler.download(
43-
'://still-invalid',
44-
downloadPath,
45-
config
46-
)
42+
NativeDownloadHandler.download('://still-invalid', downloadPath, config)
4743
).rejects.toBeDefined();
4844

4945
expect(config).toEqual(originalConfig);

0 commit comments

Comments
 (0)