使用哨兵时如何解决"API resolved without sending a response fetch"

How to solve "API resolved without sending a response fetch" when using sentry

我看了无数其他帖子,但找不到答案,为什么我在 next.js 中不断收到 API resolved without sending a response for /api/git/latest-commit, this may result in stalled requests. 错误?一旦我禁用哨兵,它就会消失,还有其他人遇到过这个问题吗?

import type { NextApiRequest, NextApiResponse } from 'next'
import { withSentry } from "@sentry/nextjs";

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
    const response = await fetch(`https://api.github.com/repos/####/####/commits?per_page=1`, {
        method: 'GET'
    });

    const data = await response.json();
    const commit = data[0]
    res.status(200).json({
        sha: {
            full: commit.sha,
            short: commit.sha.substring(0,7)
        },
        committer: commit.commit.committer.name,
        time: commit.commit.committer.date,
        html_url: commit.html_url
    })
};

export default withSentry(handler);

运行 你的代码在我这边产生了以下信息 (next 12.1.4, @sentry/nextjs 6.19.7):

[sentry] If Next.js logs a warning "API resolved without sending a response", it's a false positive, which we're working to rectify.
In the meantime, to suppress this warning, set SENTRY_IGNORE_API_RESOLUTION_ERROR to 1 in your env.
To suppress the nextjs warning, use the externalResolver API route option (see https://nextjs.org/docs/api-routes/api-middlewares#custom-config for details).

为了抑制来自 Sentry 的警告,我将此环境变量添加到 .env.development 文件中:

SENTRY_IGNORE_API_RESOLUTION_ERROR=1

为了抑制来自 Next.js API 路由的警告,我将其添加到 latest-commit.ts:

// ...

export const config = {
  api: {
    externalResolver: true,
  },
};

export default withSentry(handler);

两个警告都不再出现,数据显示 return 正确。

经过一番挖掘,这是他们对正在发生的事情的解释: https://github.com/getsentry/sentry-javascript/pull/4139

In dev, nextjs checks that API route handlers return a response to the client before they resolve, and it throws a warning if this hasn't happened. Meanwhile, in withSentry(), we wrap the res.end() method to ensure that events are flushed before the request/response lifecycle finishes.

As a result, there are cases where the handler resolves before the response is finished, while flushing is still in progress.