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>
This commit is contained in:
copilot-swe-agent[bot] 2025-12-27 08:45:34 +00:00
parent 82514e65e1
commit e1ce0f3fa9

View File

@ -21,13 +21,19 @@ export async function writeFileWithLock(
options = { encoding: options }; options = { encoding: options };
} }
try { // Ensure file exists before locking
if (!(await fileExist(filePath))) { if (!(await fileExist(filePath))) {
const fileHandle = await open(filePath, 'w'); 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(); await fileHandle.close();
} }
} catch (error) { }
throw new Error(`Failed to create file ${filePath}: ${error}`);
} }
const lockfilePath = getUniqueLockPath(filePath); const lockfilePath = getUniqueLockPath(filePath);
@ -44,7 +50,8 @@ export async function writeFileWithLock(
lockfilePath, lockfilePath,
}); });
} catch (error) { } 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 { try {
@ -53,7 +60,8 @@ export async function writeFileWithLock(
await chmod(filePath, options.mode); await chmod(filePath, options.mode);
} }
} catch (error) { } 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 { } finally {
if (release) { if (release) {
try { try {