简体   繁体   中英

Firebase Cloud Function returns INTERNAL error

I am getting the error as INTERNAL when calling a Firebase Cloud Function from my app.

Server code:

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 Code:

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);
  }

The error respose is due to accessing the properties of the custom java object passed in the function.

How to access the properties of the passed object properties?

You are calling your function with a String , but accessing it as a JSONObject .

The documentation for call() shows that it accepts a range of types including String , Map<String,?> , and JSONObject . That gives you some options for passing the food item and accessing it in your function.

  1. As you do now, convert the food item to a JSON string and pass the string. In the function code, you need to convert the string to an object with const food = JSON.parse(data) before accessing the fields, eg food.foodItem.name .

  2. If Food doesn't have many fields you could put each field in your objectHashMap and pass the map, without the conversion to JSON. Then in your function code, you could access each field without the need to use JSON.parse() .

You could get an internal error in a case when the Function instance is turned off by Google Cloud. It could happen if you have billing issues, like not enabling billing after your free trial is over.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM