如何处理 Firebase Cloud Functions 中的 Bad JSON?

How to handle Bad JSON in Firebase Cloud Functions?

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

index.js

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

这是非常简单的功能。我想使用一些负载在端点上发出 POST 请求。当我使用 Firebase Cloud Function Emulator 和带有 bad json

的 POSTman 测试 API 时
{
    "phoneNumber: "9632725300"
}

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

有这个错误

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

您宁愿更正您的 JSON...

编辑:

如果您真的希望能够发送无效的 JSON,您可以通过绕过 JSON body 解析器来实现。为此,您可以更改您的请求,将 content-type header 设置为 "text/plain"。此 content-type 将使用文本 body 解析器,它不会解析任何 JSON.

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

自行处理错误
let json;
try {
    json = JSON.parse(json);
} catch (e) {
    // Handle JSON error.
}

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

您遇到的实际上并不是服务器崩溃。事实上,从技术上讲,通过使用 Cloud Functions,您不会让服务器崩溃。 (For this reason they're called "Serverless Infrastructure") 您在 Cloud Functions 上执行的每个请求/操作都有点像一个全新的服务器。总体而言,这实际上是 Cloud Functions 的奇妙之处。 (这是一个过于简化的解释,我建议多读一点以获得更好的深入解释)

话虽这么说,据我了解,您是想弄清楚您得到的 JSON 是否无效(坏)。有时,当我不得不连接一堆外部服务时,很少,但有时,它们 return 一个糟糕的 JSON 我的 Cloud Functions 无法解析,因此会抛出错误。

解决方案是将您的 JSON.parse 放入一个单独的函数和一个 try / catch 块中,如下所示:

function safelyParseJSON (json) {
  var parsed;

  try {
    parsed = JSON.parse(json);
  } catch (e) {
    // BAD JSON, DO SOMETHING ABOUT THIS HERE.
  }

  return parsed; // will be undefined if it's a bad json!
}

function doSomethingAwesome () {
  var parsedJSON = safelyParseJSON(data);
  // Now if parsedJSON is undefined you know it was a bad one, 
  // And if it's defined you know it's a good one. 
}

有了这个辅助函数,如果你必须处理很多外部 JSON 资源,你可以很容易地确定你试图解析的 JSON 是否是好的,如果不是,您至少可以按照自己的方式处理错误。

希望对您有所帮助:)

{\n\t"phoneNumber: "9632725300"\n}

从屏幕截图中,我看到 JSON 无效或格式错误。它包含换行符 (\n) 和制表符 space (\t)。此外,密钥 "phoneNumber" 未用双引号引起来,这再次使 JSON.

无效

这是服务器应该接收的 JSON 的有效格式

{
    "phoneNumber": "9632725300"
}