feat: add error boundary to handle route errors with detailed messages

This commit is contained in:
Ardeman 2025-03-11 22:56:30 +08:00
parent ea6462f3ea
commit 2b253633a5
2 changed files with 33 additions and 2 deletions

View File

@ -74,11 +74,11 @@ export const ErrorBoundary = ({ error }: Route.ErrorBoundaryProps) => {
}
return (
<main className="container mx-auto p-4 pt-16">
<main className="container mx-auto p-4">
<h1>{message}</h1>
<p>{details}</p>
{stack && (
<pre className="w-full overflow-x-auto p-4">
<pre className="w-full p-4 whitespace-pre-wrap">
<code>{stack}</code>
</pre>
)}

View File

@ -1,3 +1,5 @@
import { isRouteErrorResponse } from 'react-router'
import { getUsers } from '~/apis/admin/get-users'
import { handleCookie } from '~/libs/cookies'
import { UsersPage } from '~/pages/dashboard-users'
@ -13,5 +15,34 @@ export const loader = async ({ request }: Route.LoaderArgs) => {
return { usersData }
}
export const ErrorBoundary = ({ error }: Route.ErrorBoundaryProps) => {
let message = 'Oops!'
let details = 'An unexpected error occurred.'
let stack: string | undefined
if (isRouteErrorResponse(error)) {
message = error.status === 404 ? '404' : 'Error'
details =
error.status === 404
? 'The requested page could not be found.'
: error.statusText || details
} else if (import.meta.env.DEV && error && error instanceof Error) {
details = error.message
stack = error.stack
}
return (
<div className="container mx-auto p-4">
<h1>{message}</h1>
<p>{details}</p>
{stack && (
<pre className="w-full p-4 whitespace-pre-wrap">
<code>{stack}</code>
</pre>
)}
</div>
)
}
const DashboardUsersLayout = () => <UsersPage />
export default DashboardUsersLayout