import { unstable_rethrow } from "next/navigation"; import { Prisma } from "@/lib/generated/prisma/client"; import { AppError, type ActionResult } from "./action-result"; export function isPrismaError(error: unknown, code: string): boolean { return error instanceof Prisma.PrismaClientKnownRequestError && error.code === code; } export async function runAction(fn: () => Promise): Promise> { try { const data = await fn(); return { success: true, data }; } catch (e) { unstable_rethrow(e); if (e instanceof AppError) { return { success: false, error: e.message, fieldErrors: e.fieldErrors }; } if (isPrismaError(e, "P2025")) { return { success: false, error: "This record was updated by someone else. Please refresh and try again." }; } if (isPrismaError(e, "P2002")) { return { success: false, error: "This record already exists." }; } console.error(e); return { success: false, error: "Something went wrong. Please try again." }; } }