Home > OS >  In a callable Firebase Cloud Function, how do i discern which code to use when i throw an error?
In a callable Firebase Cloud Function, how do i discern which code to use when i throw an error?

Time:01-31

When catching an error in a Firebase Cloud Function, the Firebase documentation for handling errors does not explain clearly which error code is appropriate to set for failed reads/writes to Firestore.

Given the following function:

exports.myCustomFunction = functions.https.onCall( async (data, context) => {
  
  if (!context.auth) {
    // Throwing this error is self explanatory and works as expected.
    throw new functions.https.HttpsError("unauthenticated", "User must be authenticated.");
  }

  const uid = context.auth.uid;
  const userQuery = admin.firestore().collection("users").where("userId", "==", uid);

  try {
   const user = await userQuery.limit(1).get();
   // do stuff...

  } catch (error) {
    // ******* THIS IS THE ERROR I NEED HELP WITH *******
    throw new functions.https.HttpsError("aborted", "user_query", {error: error});
  }

});

If a Firestore query, as i have set in the above function, fails, or for that matter, if any Firestore read/write, or a Firestore batch set, fails for any reason, what would be the appropriate error code to set?

The options seem limited. Should it be aborted or unknown?

CodePudding user response:

The error codes that you can pass to the HttpsError constructor are listed in the API documentation. If you encounter an error that your code can't resolve now or in the foreseeable future, usually you use "internal", which translates to the usual 500 HTTP status code. This lets the client know that something went wrong that was the fault of the backend and can't necessarily be fixed by a simple retry.

  •  Tags:  
  • Related