4. Throw errors JavaScript can handle
Errors with codes, thrown in Lucent and caught by code in JavaScript.
import { error } from "lucent:core";
export type Fix = { latitude: number; longitude: number; time: number };
const EARTH_RADIUS_M = 6371000;… private fixes: Fix[] = [];
add(fix: Fix): void { const last = this.fixes[this.fixes.length - 1]; if (last && fix.time < last.time) { throw error( "E_OUT_OF_ORDER", `A fix at ${fix.time} ms comes before the last one, at ${last.time} ms`, ); } this.fixes.push(fix); }
… }
summary(): TripSummary { if (this.fixes.length < 2) throw error("E_TOO_SHORT", "A trip needs at least two fixes"); let meters = 0; let topSpeed = 0; for (let i = 1; i < this.fixes.length; i++) {const trip = new Trip();for (const fix of walk) trip.add(fix);
/** Adds a fix, skipping one that arrives late instead of failing the whole trip. */function record(fix: (typeof walk)[number]): void { try { trip.add(fix); } catch (e) { if ((e as { code?: string }).code !== "E_OUT_OF_ORDER") throw e; console.warn((e as Error).message); }}
record({ latitude: 48.86, longitude: 2.33, time: 5 * 60 * 1000 }); // late: skipped
export default function App() { const [shape, setShape] = useState<number | null>(null);error(code, message) from lucent:core makes an Error with a code. JavaScript receives an ordinary Error, with the same message and code, and a stack whose first frame is the line in trip.lucent.ts that threw.
Test the code, not the message: codes are for code, messages are for people. Here, a fix that arrives late is skipped, and any other error still reaches React.
Run it
Section titled “Run it”The screen is unchanged. Metro's output shows the warning for the late fix: A fix at 300000 ms comes before the last one, at 2400000 ms.