如何在Firebase云功能中处理Bad JSON?

Ram*_*ary 14 javascript firebase firebase-realtime-database google-cloud-functions

我正在创建一个使用firebase-cloud-functions的firebase应用程序.

index.js

exports.auth = functions.https.onRequest((request, response) => {
  response.status(200).send({
    status : "Some Status"
  });
}
Run Code Online (Sandbox Code Playgroud)

这是非常简单的功能.我想POST在端点上用一些有效负载发出请求.当我使用Firebase Cloud Function Emulator和POSTman测试API时bad json

{
    "phoneNumber: "9632725300"
}
Run Code Online (Sandbox Code Playgroud)

服务器刚刚崩溃!我的问题是如何处理像这样的firebase函数中的错误请求.

有这个错误 在此输入图像描述

Sal*_*ter 5

服务器没有崩溃.您向它发送了一个错误的请求(格式错误的JSON),它完全响应状态代码400,即"错误请求".

你宁愿纠正你的JSON ......

编辑:

如果你真的希望能够发送无效的JSON,你可以通过规避JSON主体解析器来实现.为此,您可以更改您的请求以将内容类型标头设置为"text/plain".此内容类型将使用文本正文解析器,它不会解析任何JSON.

请注意,这样做将要求您自己处理JSON解析,但允许使用try-catch自己处理错误.

let json;
try {
    json = JSON.parse(json);
} catch (e) {
    // Handle JSON error.
}
Run Code Online (Sandbox Code Playgroud)

摘自https://firebase.google.com/docs/functions/http-events