feat: 添加代码片段创建功能的错误处理,新增错误页面组件

This commit is contained in:
ngc2207 2024-11-12 17:21:04 +08:00
parent a817f718d5
commit 8e869954f3
2 changed files with 41 additions and 20 deletions

View File

@ -22,27 +22,38 @@ export async function createSnippet(
formState: { message: string }, formState: { message: string },
formData: FormData formData: FormData
) { ) {
// Check the user's inputs and make sure they're valid try {
const title = formData.get("title"); // Check the user's inputs and make sure they're valid
const code = formData.get("code"); const title = formData.get("title");
if (typeof title !== "string" || title.length < 3) { const code = formData.get("code");
return { if (typeof title !== "string" || title.length < 3) {
message: "Title must be longer", 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 the user back to the root route
redirect("/"); redirect("/");
} }

View File

@ -0,0 +1,10 @@
"use client";
interface ErrorPageProps {
error: Error;
reset: () => void;
}
export default function ErrorPage({ error }: ErrorPageProps) {
return <div>{error.message}</div>;
}