Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Cloud Function returns INTERNAL error

I am getting the error as INTERNALwhen 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?

like image 534
Abhimanyu Avatar asked Jun 20 '26 01:06

Abhimanyu


1 Answers

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, e.g. 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().

like image 185
Bob Snyder Avatar answered Jun 22 '26 16:06

Bob Snyder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!