如何在 Firebase 函数中自定义错误请求响应
我编写了一个简单的 Firebase 函数,如下所示
exports.simpleFunc = functions.https.onRequest((req, res) => {
try{
JSON.parse(req.body);
res.send('Valid');
}
catch(error){
res.send('JSON is invalid');
}
});
,然后我使用 firebase emulator:start
在本地运行此函数
,之后我使用 Postman 通过发送无效的 JSON 值来测试此函数,
{
"firstName": "User 1",
"email": "[email protected]",
"description": "\u000g" >> this is an invalid value
}
我希望我的函数应返回我的错误消息 JSON 无效
。然而,它返回了整个 HTML 页面,并显示错误 SyntaxError: Unexpected token g in JSON atposition xx at JSON.parse (
所以我的问题是:我如何发送我的错误消息而不是整个 HTML 字符串?
我在这里发现了同样的问题 https://github.com/firebase/firebase-functions/issues/364
但这不是我的期望。
I wrote a simple Firebase function like below
exports.simpleFunc = functions.https.onRequest((req, res) => {
try{
JSON.parse(req.body);
res.send('Valid');
}
catch(error){
res.send('JSON is invalid');
}
});
then I ran this function locally by using firebase emulator:start
after that I used Postman to test this function by sending an invalid JSON values
{
"firstName": "User 1",
"email": "[email protected]",
"description": "\u000g" >> this is an invalid value
}
I expect that my function should return my error message JSON is invalid
. However it returned a whole HTML page with an error SyntaxError: Unexpected token g in JSON at position xx at JSON.parse (<anonymous>)
So my question is: How can I send my error message instead of the whole HTML string?
I have found the same issue here
https://github.com/firebase/firebase-functions/issues/364
But it's not my expectation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果将 JSON 声明为 JSON,则无法捕获 JSON 解析错误。要捕获它,不要声明为 JSON,而是将其声明为文本并在客户端上解析它。请参阅下面的图片以供参考。
将其声明为
JSON
(请参阅绿色突出显示的部分):将其声明为
Text
(请参阅绿色突出显示的部分):There's no way you can expect to catch the error parsing of JSON if you declared it as JSON. To catch it, instead of declaring as JSON, declare it as text and parse it on the client. See images below for reference.
Declaring it as
JSON
(See green highlighted section):Declaring it as
Text
(See green highlighted section):