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.
This commit is contained in:
Grovy311 2026-08-07 17:17:44 +02:00
parent bfcddee128
commit 01a024f048

View file

@ -26,7 +26,9 @@ export async function calculateCableSizingHandler(req: Request, res: Response) {
const result = calculateCableSizing(input);
const alerts = buildCableSizingAlerts(input, result);
const entry = await cableSizingCalculationRepository.create({
let entry;
try {
entry = await cableSizingCalculationRepository.create({
id: randomUUID(),
projectId: context?.projectId ?? null,
circuitId: context?.circuitId ?? null,
@ -35,6 +37,23 @@ export async function calculateCableSizingHandler(req: Request, res: Response) {
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 });
}