我的/app/API/auth/route.ts文件:
import { redirect } from 'next/navigation';
export async function GET(req: Request) {
try {
redirect('/dashboard');
} catch (error) {
console.log(error);
redirect('/');
}
}
我意识到,当我在try catch中重定向时,我得到了错误:
Error: NEXT_REDIRECT
at getRedirectError (webpack-internal:///(sc_server)/./node_modules/next/dist/client/components/redirect.js:40:19)
at redirect (webpack-internal:///(sc_server)/./node_modules/next/dist/client/components/redirect.js:46:11)
at GET (webpack-internal:///(sc_server)/./app/api/auth/route.ts:23:66)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:244:37) {
digest: 'NEXT_REDIRECT;replace;/dashboard'
}
当我摆脱try catch时,一切都很好:
export async function GET(req: Request) {
redirect('/dashboard')
}
这和预期的一样。我需要try和catch,因为这是一个auth路由,我需要一些错误处理,因为请求可能会失败,我已经省略了auth功能,因为我意识到这只发生在一个简单的try和catch上。
或者,如果Next 13在/API路由中有其他错误处理方法,请告诉我。
1条答案
按热度按时间mcdcgff01#
这是因为在内部,redirect()抛出了一个Error。参见https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect.ts#L16-L41C2