Is it possible to know which route segment threw an error inside `error.js`?
Answered
Abno posted this in #help-forum
AbnoOP
So, I have the following structure on the project I'm working on (simplified)
The following are the requirements for handling errors in the application:
1. 404 and 500 errors will redirect to
2. If a 500 error occurs on
404 is handled without problems by
If I know which route threw an error, I can implement requirement 2 by testing if it was
Is this possible?
.
├── layout.tsx
├── not-found.tsx
├── error.tsx
├── global-error.tsx
├── page.tsx
└── [lang]/
└── dashboard/
├── page.tsx
├── error.tsx
└── products/
└── page.tsxThe following are the requirements for handling errors in the application:
1. 404 and 500 errors will redirect to
/dashboard route, showing a toast describing the error.2. If a 500 error occurs on
/dashboard itself, it should log the user out instead.404 is handled without problems by
not-found.tsx and throwing an error inside dashboard/page.tsx gets caught by the error and signs the user out successfully. The issue is handling errors thrown in dashboard/products/page.tsx. Since the error boundary is wrapping the entire dashboard route segment, it also catches the errors from any nested routes.If I know which route threw an error, I can implement requirement 2 by testing if it was
/dashboard and only signing out in that case, and otherwise just the behavior of requirement 1.Is this possible?
Answered by Abno
Implemented it using route groups. The
error.tsx now only affects the index group and all other routes fallback to main error.tsx.
├── layout.tsx
├── not-found.tsx
├── error.tsx
├── global-error.tsx
├── page.tsx
└── [lang]/
└── dashboard/
├── (index)/
│ ├── page.tsx
│ └── error.tsx
└── products/
└── page.tsx1 Reply
AbnoOP
Implemented it using route groups. The
error.tsx now only affects the index group and all other routes fallback to main error.tsx.
├── layout.tsx
├── not-found.tsx
├── error.tsx
├── global-error.tsx
├── page.tsx
└── [lang]/
└── dashboard/
├── (index)/
│ ├── page.tsx
│ └── error.tsx
└── products/
└── page.tsxAnswer