【问题标题】:Firebase Cloud Function returns INTERNAL errorFirebase 云函数返回内部错误
【发布时间】:2019-09-03 21:06:04
【问题描述】:

当我从我的应用调用 Firebase 云函数时,我收到了 INTERNAL 的错误。

服务器代码:

exports.addToCart = functions.https.onCall((data, context) => { 
  // Checking that the user is authenticated.
  if (!context.auth) {
    // Throwing an HttpsError so that the client gets the error details.
    throw new functions.https.HttpsError(
      "failed-precondition",
      "The function must be called " + "while authenticated."
    );
  }

  // Get data
  const food = data.food;

  // Get user details
  const uid = context.auth.uid;

  console.log("User id " + uid);
  console.log("Food name " + food.name);

  return "Added to cart successfully."
});

Java 代码:

addToCartTask(foodItem)
  .addOnSuccessListener(s -> {
    Log.e(TAG, "Success : " + s);
  })
  .addOnFailureListener(e -> {
    Log.e(TAG, "Error : " + e.getLocalizedMessage());
  });

private Task<String> addToCartTask(Food foodItem) {
  // Create the arguments to the callable function.
  Map<String, Object> objectHashMap = new HashMap<>();
  objectHashMap.put("foodItem", foodItem);

  Gson gson = new Gson();
  String data = gson.toJson(objectHashMap);

  return firebaseFunctions
    .getHttpsCallable("addToCart")
    .call(data);
  }

错误响应是由于访问了函数中传递的自定义 java 对象的属性。

如何访问传递的对象属性的属性?

【问题讨论】:

    标签: android firebase google-cloud-functions


    【解决方案1】:

    您正在使用String 调用您的函数,但以JSONObject 的形式访问它。

    documentation for call() 表明它接受一系列类型,包括StringMap&lt;String,?&gt;JSONObject。这为您提供了一些选项来传递食物项并在您的函数中访问它。

    1. 和现在一样,将食物项转换为 JSON 字符串并传递该字符串。在函数代码中,您需要在访问字段之前将字符串转换为带有const food = JSON.parse(data) 的对象,例如food.foodItem.name.

    2. 如果 Food 没有很多字段,您可以将每个字段放入您的 objectHashMap 并传递映射,而无需转换为 JSON。然后在您的函数代码中,您可以访问每个字段而无需使用JSON.parse()

    【讨论】:

    • 到达相同的解决方案(JSON解析),忘记在这里更新。感谢您的回复。
    猜你喜欢
    • 2019-08-21
    • 1970-01-01
    • 2021-05-06
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多