我使用Next.js和下一次连接来处理中间件。
但是,当我在getServerSideProps中使用几个中间件时,我在试图处理错误时遇到了问题。
这是我在getServerSideProps中的代码,我只是使用几个中间件创建了一个处理程序,然后所有这些中间件都运行,身份验证是成功的,用户数据应该传递给响应,但是如果有任何失败,错误应该被捕获并返回一个重定向到'/login'页面。
import nextConnect from 'next-connect';
import { openDBConnection, retrieveUserInfo } from '@/middlewares/database';
import { verifySessionCookie } from '@/middlewares/firebaseSession';
...
export const getServerSideProps = async ({ req, res }) => {
const handler = nextConnect()
.use(verifySessionCookie)
.use(openDBConnection)
.use(retrieveUserInfo);
try {
await handler.run(req, res);
return {
props: {
user: req.user,
},
};
} catch (e) {
console.log(e);
return {
redirect: {
destination: '/login',
permanent: false,
}
};
}
}我没有在任何中间件中定义任何try/catch块,所以如果发生错误,可以在任何api页面或getServerSideProps块中处理。
当只有一个中间程序verifySessionCookie时,似乎一切都正常,当调用await handler.run(req, res)并在catch块中处理时,会返回错误。
但是,当使用代码中所示的3个中间件时,如果第一个中间件失败(verifySessionCookie),则不会在catch块中处理错误。
我尝试在每个中间件中使用一个next()子句进行finally调用,以这种方式在getServerSideProps中捕获错误,但是:
也许我在这里做错了什么,或者下一个-连接并不打算用这种方式。我不知道如何处理这个错误,以防一个中间件和其他所有的中间件都没有被执行。也许我应该在getServerSideProps中使用(req,res)参数调用独立的异步函数,并停止使用这个下一个连接插件。
发布于 2021-08-30 16:51:48
下一次连接上的文档说您可以在nextConnect上添加onError
function onError(err, req, res, next) {
logger.log(err);
res.status(500).end(err.toString());
// OR: you may want to continue
next();
}
const handler = nextConnect({ onError });或者在您的中间件中,您可以通过req传递一些值,以使其更具可定制性。
在中间件中,您可以添加一个try/catch块以使用req传递不同的值。
类似于:
export const middlewareExample = (req, res, next) => {
try {
// ...
req.condition = {
status: 'succuss, ...',
message: '...',
data: {
// ...
}
}
next();
} catch(error) {
res.status(...).end(...);
// OR: you may want to continue
req.condition = {
status: 'error, ...',
message: '...',
data: {
// ...
}
}
next();
}
}export const getServerSideProps = async ({ req, res }) => {
const handler = nextConnect()
.use(verifySessionCookie)
.use(openDBConnection)
.use(retrieveUserInfo);
await handler.run(req, res);
if (req.condation.status === 'succuss') {
return {
props: {
user: req.user,
},
};
} else {
console.log(req.condation.message);
return {
redirect: {
destination: '/login',
permanent: false,
}
};
}
})我希望这能帮到你。
https://stackoverflow.com/questions/66763973
复制相似问题