himself65
(himself65)
1
For exmaple I have a page.tsx which is a server component
export default async function Page() {
await checkUserPermission(...)
const data = await getData()
const data2 = await getData2()
// ...
}
Let’s assume this server component might throw UserNotFound
, UserNoPermission
, DataNotFound
, DataNoPermisison
, Data2NotFound
, or Data2NoPermisison
… (even more)
The question is: How do I show the error to user side properly?
The issue is, I know there’s error.tsx
, but it’s in client side, I have only get server error digest, which is totally useless for my customer…
If you suggest me to write everything into promise and bypass to client component, NO, that’s waste too much work.
All unhandled errors will land in error.tsx, so if you want to show them in your UI then you need to catch them and return the appropriate UI
import { notFound, redirect } from 'next/navigation'
export default async function Page() {
await requireUser()
const result = await getData()
if (!result.ok) {
if (result.error instanceof DataNotFound) notFound()
return (
<main>
<h1>Access Denied</h1>
<p>You don’t have permission to view this content.</p>
</main>
)
}
return (
<main>
<h1>Welcome</h1>
{/* Render with result.value */}
</main>
)
}
async function requireUser() {
try {
const user = await getUser()
return user
} catch (error) {
if (error instanceof UserNotFound) notFound()
if (error instanceof UserNoPermission) redirect('/login')
throw error
}
}
async function getData() {
try {
const value = await actuallyGetData()
return { ok: true, value } as const
} catch (error) {
return { ok: false, error } as const
}
}
1 Like