fix: return clean errors and refund quota on AI provider failures

AI routes had no consistent error handling — a provider failure (e.g.
OpenRouter returning a degraded-model error) crashed the route as an
uncaught 500 and, worse, still charged the user's monthly aiCall
quota for a request that never succeeded.

Adds withAiQuota()/aiErrorResponse() (lib/ai/ai-error.ts) and applies
them across all 12 AI generation routes: charges the quota, runs the
AI call, refunds the credit and returns a clean user-facing message
if it throws. Frontend needs no changes — existing dialogs already
toast whatever `error` string comes back.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-02 12:32:31 +02:00
parent e5d1080fb9
commit 524310433c
16 changed files with 325 additions and 165 deletions
+6 -17
View File
@@ -3,7 +3,7 @@ import { z } from "zod";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
import { withAiQuota } from "@/lib/ai/ai-error";
import { importFromPhoto } from "@/lib/ai/features/import-photo";
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
@@ -28,15 +28,6 @@ export async function POST(req: NextRequest) {
const userId = session!.user.id;
const locale = (session!.user as { locale?: string }).locale ?? "en";
try {
await checkAndIncrementTierLimit(userId, session!.user.tier as "free" | "pro", "aiCall");
} catch (err: unknown) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "AI call limit reached for your tier" }, { status: 403 });
}
throw err;
}
const aiConfig = await getModelConfigForUseCase(userId, "vision");
// Fall back to vision-capable defaults if no explicit model configured
@@ -45,13 +36,11 @@ export async function POST(req: NextRequest) {
else if (aiConfig.provider === "anthropic") aiConfig.model = "claude-sonnet-4-6";
}
let recipe;
try {
recipe = await importFromPhoto(parsed.data.imageBase64, parsed.data.mimeType, aiConfig, locale);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "AI analysis failed";
return NextResponse.json({ error: msg }, { status: 502 });
}
const result = await withAiQuota(userId, session!.user.tier as "free" | "pro", () =>
importFromPhoto(parsed.data.imageBase64, parsed.data.mimeType, aiConfig, locale)
);
if (!result.ok) return result.response;
const recipe = result.data;
const newRecipeId = crypto.randomUUID();
const now = new Date();