From e1ce0f3fa996be78199b9c00077d3a4c465292d0 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 27 Dec 2025 08:45:34 +0000 Subject: [PATCH] Improve error handling based on code review feedback - Use finally block to ensure file handle is closed even on error - Extract error messages properly using instanceof Error check - Improve error message formatting for better debugging Co-authored-by: whyour <22700758+whyour@users.noreply.github.com> --- back/shared/utils.ts | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/back/shared/utils.ts b/back/shared/utils.ts index 967f3d8d..8d650037 100644 --- a/back/shared/utils.ts +++ b/back/shared/utils.ts @@ -21,13 +21,19 @@ export async function writeFileWithLock( options = { encoding: options }; } - try { - if (!(await fileExist(filePath))) { - const fileHandle = await open(filePath, 'w'); - await fileHandle.close(); + // Ensure file exists before locking + if (!(await fileExist(filePath))) { + let fileHandle; + try { + fileHandle = await open(filePath, 'w'); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + throw new Error(`Failed to create file ${filePath}: ${errorMessage}`); + } finally { + if (fileHandle) { + await fileHandle.close(); + } } - } catch (error) { - throw new Error(`Failed to create file ${filePath}: ${error}`); } const lockfilePath = getUniqueLockPath(filePath); @@ -44,7 +50,8 @@ export async function writeFileWithLock( lockfilePath, }); } catch (error) { - throw new Error(`Failed to acquire lock for ${filePath}: ${error}`); + const errorMessage = error instanceof Error ? error.message : String(error); + throw new Error(`Failed to acquire lock for ${filePath}: ${errorMessage}`); } try { @@ -53,7 +60,8 @@ export async function writeFileWithLock( await chmod(filePath, options.mode); } } catch (error) { - throw new Error(`Failed to write to file ${filePath}: ${error}`); + const errorMessage = error instanceof Error ? error.message : String(error); + throw new Error(`Failed to write to file ${filePath}: ${errorMessage}`); } finally { if (release) { try {