From 01a024f0484b1b9e971c7d122b1ff7a1333f6a6f Mon Sep 17 00:00:00 2001 From: Grovy311 Date: Fri, 7 Aug 2026 17:17:44 +0200 Subject: [PATCH] cable-sizing: return 400 instead of 500 for an unknown context circuitId/projectId context.circuitId/projectId are caller-supplied audit-log metadata, not used in the calculation itself. A stale or unknown id (e.g. a circuit deleted between page load and this request) violated the foreign key and fell through to the generic 500 handler; catch it and report it as a normal validation error instead. --- .../controllers/cable-sizing.controller.ts | 37 ++++++++++++++----- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/src/server/controllers/cable-sizing.controller.ts b/src/server/controllers/cable-sizing.controller.ts index 7c08999..e0b628e 100644 --- a/src/server/controllers/cable-sizing.controller.ts +++ b/src/server/controllers/cable-sizing.controller.ts @@ -26,15 +26,34 @@ export async function calculateCableSizingHandler(req: Request, res: Response) { const result = calculateCableSizing(input); const alerts = buildCableSizingAlerts(input, result); - const entry = await cableSizingCalculationRepository.create({ - id: randomUUID(), - projectId: context?.projectId ?? null, - circuitId: context?.circuitId ?? null, - equipmentIdentifier: context?.equipmentIdentifier ?? null, - input, - result, - appliedToCircuit: 0, - }); + let entry; + try { + entry = await cableSizingCalculationRepository.create({ + id: randomUUID(), + projectId: context?.projectId ?? null, + circuitId: context?.circuitId ?? null, + equipmentIdentifier: context?.equipmentIdentifier ?? null, + input, + result, + appliedToCircuit: 0, + }); + } catch (error) { + // context.circuitId/projectId are caller-supplied and only used for the + // audit-log entry, not the calculation itself - a stale or unknown id + // (e.g. a circuit deleted between page load and this request) should be + // a normal 400, not a raw 500 from the foreign-key constraint. + if ( + error && + typeof error === "object" && + "code" in error && + (error as { code?: string }).code === "SQLITE_CONSTRAINT_FOREIGNKEY" + ) { + return res + .status(400) + .json({ error: "Unknown context.projectId or context.circuitId" }); + } + throw error; + } return res.status(201).json({ calculationId: entry.id, result, alerts }); }