008 错误处理 try/catch
目录
本文对应 Next.js Learn 入门教程的第 13 章。
try/catcherror.tsxnot-found.tsx
try/catch & error.tsx
try/catch
ts
export async function createInvoice(formData: FormData) {
const { customerId, amount, status } = CreateInvoice.parse({
customerId: formData.get('customerId'),
amount: formData.get('amount'),
status: formData.get('status'),
});
const amountInCents = amount * 100;
const date = new Date().toISOString().split('T')[0];
try {
await sql`
INSERT INTO invoices (customer_id, amount, status, date)
VALUES (${customerId}, ${amountInCents}, ${status}, ${date})
`;
} catch (error) {
return {
message: 'Database Error: Failed to Create Invoice.',
};
}
revalidatePath('/dashboard/invoices');
redirect('/dashboard/invoices');
}redirect
Note how redirect is being called outside of the try/catch block. This is because redirect works by throwing an error, which would be caught by the catch block.
To avoid this, you can call redirect after try/catch. redirect would only be reachable if try is successful.
(原文中有具体例子……)
error.tsx
The error.tsx file can be used to define a UI boundary for a route segment. It serves as a catch-all for unexpected errors and allows you to display a fallback UI to your users.
Inside your /dashboard/invoices folder, create a new file called error.tsx and paste the following code:
(代码略)
为何页面右下角仍显示 Unhandled Runtime Error Error: Failed to Delete Invoice
notFound
(略)
https://nextjs.org/learn/dashboard-app/error-handling#handling-404-errors-with-the-notfound-function

That's something to keep in mind, notFound will take precedence over error.tsx, so you can reach out for it when you want to handle more specific errors!
