From 8e869954f30d283c2bc0d9e4d1eeef5f1908f84f Mon Sep 17 00:00:00 2001 From: ngc2207 Date: Tue, 12 Nov 2024 17:21:04 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E7=89=87=E6=AE=B5=E5=88=9B=E5=BB=BA=E5=8A=9F=E8=83=BD=E7=9A=84?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E5=A4=84=E7=90=86=EF=BC=8C=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E9=A1=B5=E9=9D=A2=E7=BB=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/actions/index.ts | 51 +++++++++++++++++++++------------- src/app/snippets/new/error.tsx | 10 +++++++ 2 files changed, 41 insertions(+), 20 deletions(-) create mode 100644 src/app/snippets/new/error.tsx diff --git a/src/actions/index.ts b/src/actions/index.ts index 985c956..4b4d314 100644 --- a/src/actions/index.ts +++ b/src/actions/index.ts @@ -22,27 +22,38 @@ export async function createSnippet( formState: { message: string }, formData: FormData ) { - // Check the user's inputs and make sure they're valid - const title = formData.get("title"); - const code = formData.get("code"); - if (typeof title !== "string" || title.length < 3) { - return { - message: "Title must be longer", - }; + try { + // Check the user's inputs and make sure they're valid + const title = formData.get("title"); + const code = formData.get("code"); + if (typeof title !== "string" || title.length < 3) { + return { + message: "Title must be longer", + }; + } + if (typeof code !== "string" || code.length < 10) { + return { + message: "Code must be longer", + }; + } + // Create a new record in the database + await db.snippet.create({ + data: { + title: title, + code: code, + }, + }); + } catch (err: unknown) { + if (err instanceof Error) { + return { + message: err.message, + }; + } else { + return { + message: "Something went wrong...", + }; + } } - if (typeof code !== "string" || code.length < 10) { - return { - message: "Code must be longer", - }; - } - // Create a new record in the database - const snippet = await db.snippet.create({ - data: { - title: title, - code: code, - }, - }); - console.log(snippet); // Redirect the user back to the root route redirect("/"); } diff --git a/src/app/snippets/new/error.tsx b/src/app/snippets/new/error.tsx new file mode 100644 index 0000000..8017d60 --- /dev/null +++ b/src/app/snippets/new/error.tsx @@ -0,0 +1,10 @@ +"use client"; + +interface ErrorPageProps { + error: Error; + reset: () => void; +} + +export default function ErrorPage({ error }: ErrorPageProps) { + return
{error.message}
; +}