#286: request() now throws C2ApiError — message is FastAPI's `detail` or a plain sentence for the status (401/403/404/429/5xx), with toString() so the many String(e) call sites read cleanly. status/body stay on the error; the Discord parsers rebuild the legacy "C2 API error N: body" text via legacyErrorText(), so their invite/code parsing is unchanged. #284: Resolve, Regenerate summary, alert-rule toggle/delete/load, Acknowledge, trip deletes, system delete and Restart OP25 now surface failures (ErrorBanner where the page has one, alert() where the page already uses it). Rules tab no longer says "No alert rules configured" when the load failed. Confirms added for Resolve (no reopen path exists), rule delete and trip delete. Reopen deliberately not built — manual resolve doesn't set resolved_at, so reopening is a lifecycle change. Frontend unverified: no Node on the authoring box (#207). Closes #286 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
6d667e81c9
commit
f16f0a9f93
@@ -1,4 +1,5 @@
|
||||
import { auth } from "@/lib/firebase";
|
||||
import { C2ApiError } from "@/lib/c2error";
|
||||
import type {
|
||||
AreaContext, CameraProviderAdmin, CamerasResponse, Ny511Response, OutageProviderAdmin, OutagesResponse, TalkgroupPending,
|
||||
WeatherAlertsResponse, WindResponse,
|
||||
@@ -19,7 +20,7 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
...(options?.headers as Record<string, string> | undefined),
|
||||
},
|
||||
});
|
||||
if (!res.ok) throw new Error(`C2 API error ${res.status}: ${await res.text()}`);
|
||||
if (!res.ok) throw new C2ApiError(res.status, await res.text());
|
||||
if (res.status === 204) return undefined as T;
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Error thrown by every C2 API request (server-26#286).
|
||||
*
|
||||
* `message` is a sentence a user can read — FastAPI's `detail` when the
|
||||
* server sent one, otherwise a plain mapping of the status. The raw status
|
||||
* and body stay on the error for callers that need the structured parts
|
||||
* (the Discord parsers read `invite`/`code` out of `body`).
|
||||
*/
|
||||
export class C2ApiError extends Error {
|
||||
readonly status: number;
|
||||
readonly body: string;
|
||||
|
||||
constructor(status: number, body: string) {
|
||||
super(humanMessage(status, body));
|
||||
this.name = "C2ApiError";
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
// Call sites render String(e); without this it reads "C2ApiError: …".
|
||||
toString(): string {
|
||||
return this.message;
|
||||
}
|
||||
}
|
||||
|
||||
function detailOf(body: string): string | null {
|
||||
try {
|
||||
const parsed = JSON.parse(body);
|
||||
const d = parsed?.detail;
|
||||
if (typeof d === "string" && d.trim()) return d;
|
||||
// pydantic validation errors: [{loc, msg, type}, ...]
|
||||
if (Array.isArray(d)) {
|
||||
const msgs = d.map((x: { msg?: unknown }) => (typeof x?.msg === "string" ? x.msg : null)).filter(Boolean);
|
||||
if (msgs.length) return msgs.join("; ");
|
||||
}
|
||||
} catch {
|
||||
/* not JSON */
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function humanMessage(status: number, body: string): string {
|
||||
const detail = detailOf(body);
|
||||
if (status === 401) return "Your session has expired. Sign in again.";
|
||||
if (status === 403) return detail ? `Not allowed: ${detail}` : "You don't have permission to do that.";
|
||||
if (detail) return detail;
|
||||
if (status === 404) return "Not found. It may have been deleted.";
|
||||
if (status === 429) return "Too many requests. Wait a moment and try again.";
|
||||
if (status >= 500) return "The server hit an error. Try again in a moment.";
|
||||
return `Request failed (${status}).`;
|
||||
}
|
||||
|
||||
/** Message for any caught value — use in catch blocks instead of String(e). */
|
||||
export function errorMessage(e: unknown): string {
|
||||
if (e instanceof Error) return e.message;
|
||||
return String(e);
|
||||
}
|
||||
|
||||
/** Rebuilds the legacy `C2 API error <status>: <body>` string for the
|
||||
* Discord parsers, which predate C2ApiError and match on that shape. */
|
||||
export function legacyErrorText(err: unknown): string {
|
||||
if (err instanceof C2ApiError) return `C2 API error ${err.status}: ${err.body}`;
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
// (routers/discord.py GET /discord/admin/overview, routers/tokens.py), and
|
||||
// small helpers shared by /settings/discord and /tokens (server-26#213).
|
||||
|
||||
import { legacyErrorText } from "@/lib/c2error";
|
||||
|
||||
export interface RadioBotLease {
|
||||
node_id: string;
|
||||
lease_id?: string;
|
||||
@@ -160,7 +162,7 @@ export const SNOWFLAKE = /^\d{15,21}$/;
|
||||
* so "no bot in this server" can render its invite links.
|
||||
*/
|
||||
export function parseC2Error(err: unknown): { message: string; invite: { name: string; invite_url: string | null }[] } {
|
||||
const raw = err instanceof Error ? err.message : String(err);
|
||||
const raw = legacyErrorText(err);
|
||||
const m = raw.match(/^C2 API error (\d+): ([\s\S]*)$/);
|
||||
if (m) {
|
||||
try {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
// browser: the code exchange happens in c2-core.
|
||||
|
||||
import { auth } from "@/lib/firebase";
|
||||
import { C2ApiError } from "@/lib/c2error";
|
||||
|
||||
const BASE = process.env.NEXT_PUBLIC_C2_URL ?? "http://localhost:8000";
|
||||
|
||||
@@ -24,7 +25,7 @@ async function send<T>(method: "POST" | "PUT" | "DELETE", path: string, body?: o
|
||||
},
|
||||
...(body ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
if (!res.ok) throw new Error(`C2 API error ${res.status}: ${await res.text()}`);
|
||||
if (!res.ok) throw new C2ApiError(res.status, await res.text());
|
||||
if (res.status === 204) return undefined as T;
|
||||
return res.json();
|
||||
}
|
||||
@@ -58,7 +59,7 @@ export async function startDiscordOAuth(req: OAuthStartRequest): Promise<OAuthSt
|
||||
try {
|
||||
raw = await post("/discord/oauth/start", req);
|
||||
} catch (err) {
|
||||
if (err instanceof Error && /^C2 API error 404:/.test(err.message)) throw new OAuthNotConfigured(err.message);
|
||||
if (err instanceof C2ApiError && err.status === 404) throw new OAuthNotConfigured(err.message);
|
||||
throw err;
|
||||
}
|
||||
const url = raw.url ?? raw.authorize_url ?? "";
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// Shapes returned by c2-core app/routers/discord_web.py. No token strings —
|
||||
// the server never sends them to the browser.
|
||||
|
||||
import { legacyErrorText } from "@/lib/c2error";
|
||||
|
||||
export type StreamState =
|
||||
| "pending"
|
||||
| "connecting"
|
||||
@@ -131,7 +133,7 @@ function reasonOf(b: Record<string, unknown>): string | null {
|
||||
/** c2api's request() throws `C2 API error <status>: <body>`. Pull the
|
||||
* detail, code and invite links back out of a JSON body. */
|
||||
export function parseC2Error(err: unknown): ParsedC2Error {
|
||||
const raw = err instanceof Error ? err.message : String(err);
|
||||
const raw = legacyErrorText(err);
|
||||
const m = raw.match(/^C2 API error (\d+): ([\s\S]*)$/);
|
||||
const status = m ? Number(m[1]) : null;
|
||||
const idx = raw.indexOf(": ");
|
||||
|
||||
Reference in New Issue
Block a user