如何使用 next-connect 在 Next.js 中处理 getServerSideProps 中的错误

问题描述

我使用 Next.js 和 next-connect 来处理中间件。

但是当我在 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 中被捕获,但是:

  • verifySessionCookie 执行,但失败。
  • openDBConnection 执行,它不会失败。
  • retrieveUserInfo 执行,但失败。

也许我在这里做错了什么,或者 next-connect 不打算以这种方式使用。我不知道如果一个中间件和其他所有中间件都没有执行,我该如何处理错误。也许我应该在 getServerSideProps 中使用 (req,res) 参数调用独立的异步函数,并停止使用这个 next-connect 插件

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...