Next.js中API端点的自定义错误响应



我想创建自定义响应的错误,如404 &500在我的Next.js应用程序。我知道你可以在/pages目录中创建自定义错误页面,但对于我的pages/api端点,我希望错误是JSON格式,我很确定这在/pages目录中是不可能的-当我返回JSON时,它会抛出一个错误,因为它想要一个React组件。

有谁能告诉我怎么做吗?

我以前在NextJS API层中这样做过。

let res1, res2, res3;
try {
res1 = await getIdentity(authToken, user.id);
const username = (res1 as { userName: string }).userName;
res2 = await postIdentity(authToken, username, user.password);
res3 = await putIdentity(authToken, user.id, username, user.newPassword);
} catch (e) {
// refine your own error here if needed
return res.status(200).json(e);
}

您可以看到所有getIdentity,postIdentityputIdentity都是api调用,可以生成从200到405的任何内容。如果我捕捉到任何东西,我返回200和我自己的错误处理代码。

最新更新