【发布时间】:2020-04-01 16:00:14
【问题描述】:
我有一个 HTTP 函数每秒执行几次(我没有确切的统计数据)。
有时,请求会按预期返回数据,有时会返回以下错误文本:
<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>500 Server Error</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Server Error</h1>
<h2>The server encountered an error and could not complete your request.<p>Please try again in 30 seconds.</h2>
<h2></h2>
</body></html>
发生这种情况时,我的所有 HTTP 函数都会发生这种情况。 5 分钟后发出相同的请求通常会奏效。
现在,我可以想象它在我的代码中是一个错误,但我正在使用中间件来捕获所有错误并以 JSON 响应!
这是我导出的云函数:
const app = express();
app.use(cors({origin: true, credentials: true})); // Allow cross-origin requests
app.get('/', this.reportRequest.bind(this));
app.use(errorMiddleware); // Handle errors
export const report = functions.https.onRequest(app);
这里是errorMiddleware:
export const errorMiddleware: ErrorRequestHandler = async (e, req, res, next) => {
const executionId = req.header('function-execution-id');
const message = 'message' in e ? e.message : e;
const code = e.code && e.code > 200 && e.code < 600 ? e.code : 500;
res.status(code).json({message, executionId});
next();
};
【问题讨论】:
-
您遇到什么错误?我在使用 Cloud Functions 和调用外部 API(Google API)时遇到了一些问题。将开始出错。
-
我得到的错误出现在第一个代码块中,它只是那个 HTML 代码和状态代码 500。
The server encountered an error and could not complete your request.<p>Please try again in 30 seconds.。我不确定我是否太快调用 API。有没有办法检查这个? -
您能提供更多细节吗?你用这个功能做什么?您是否在云功能中渲染网站?我使用 Cloud Functions 作为我的 Web 应用程序的后端,所以我只从请求中得到错误,而不是 html 文档。
-
我使用 Firebase 云函数作为 API。例如,此报告功能列出了来自云 Firestore 的一些项目并将它们作为 JSON 返回。我绝不会返回 HTML,尽管如此,这是输出。我怀疑它与 firebase 相关,而不是 express 功能。
-
也许你的代码顺序有问题。据我所知,您必须将 app.use(middleware) 放在 app.get() 之前才能获得 JSON 响应,因为代码是连续的。但这不能解释为什么函数停止 5 分钟的行为。 reportRequest 回调函数有什么作用?
标签: firebase express google-cloud-functions