feat: mejorar el manejo de errores en la inicialización de datos y asegurar la preservación de fallos originales

This commit is contained in:
David Arranz 2026-10-25 19:18:05 +01:00
parent b7df37707b
commit da52788e65
2 changed files with 14 additions and 2 deletions

View File

@ -69,3 +69,13 @@ it("reports connection cleanup errors", async () => {
connection.close.mockRejectedValue(new Error("synthetic private detail")); connection.close.mockRejectedValue(new Error("synthetic private detail"));
await expect(initializeData({ ...options, admin: true })).rejects.toThrow("connection cleanup"); await expect(initializeData({ ...options, admin: true })).rejects.toThrow("connection cleanup");
}); });
it("preserves the original failure when cleanup also fails", async () => {
const cause = new Error("Account failed");
users.mockRejectedValue(cause);
connection.close.mockRejectedValue(new Error("Close failed"));
await expect(initializeData({ ...options, admin: true })).rejects.toMatchObject({
message: "Data initialization failed during accounts.", cause,
});
expect(connection.close).toHaveBeenCalledTimes(1);
});

View File

@ -19,6 +19,7 @@ export const initializeData = async (options: DataInitializationOptions): Promis
} }
let adapter: ReturnType<typeof createSequelizeAdapter> | undefined; let adapter: ReturnType<typeof createSequelizeAdapter> | undefined;
let stage = "connection"; let stage = "connection";
let failure: Error | undefined;
try { try {
// Seed errors and SQL logging must not expose account data or password hashes. // Seed errors and SQL logging must not expose account data or password hashes.
adapter = createSequelizeAdapter({ logging: false }); adapter = createSequelizeAdapter({ logging: false });
@ -45,12 +46,13 @@ export const initializeData = async (options: DataInitializationOptions): Promis
} }
} catch (cause) { } catch (cause) {
// Only this static message is printed by the CLI; the original cause stays private. // Only this static message is printed by the CLI; the original cause stays private.
throw new Error(`Data initialization failed during ${stage}.`, { cause }); failure = new Error(`Data initialization failed during ${stage}.`, { cause });
} finally { } finally {
try { try {
await adapter?.connection.close(); await adapter?.connection.close();
} catch (cause) { } catch (cause) {
throw new Error("Data initialization failed during connection cleanup.", { cause }); failure ??= new Error("Data initialization failed during connection cleanup.", { cause });
} }
} }
if (failure) throw failure;
}; };