You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Callable Function返回500错误,求排查修复

Firebase Callable Function 500错误修复

问题核心

将Firebase Function从HTTP调用改为Callable Function后返回500错误,需求是根据ID从Firestore的quizzes集合获取对应测验文档。

原函数代码的问题

  1. Callable Function参数逻辑错误:onCall的回调参数是单个context对象,而非(request, response),客户端传递的参数存储在context.data中。
  2. 参数获取路径错误:原代码中request.queryid完全不符合Callable Function的参数结构,应从context.data.id获取客户端传入的ID。
  3. 错误处理不规范:捕获异常时直接拼接error对象会导致信息格式化异常,需使用error.message提取具体错误信息。

修正后的函数代码

// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const { logger } = require("firebase-functions");

// Dependencies for callable functions.
const { onCall, HttpsError } = require("firebase-functions/v2/https");

// The Firebase Admin SDK to access Firestore.
const { initializeApp } = require("firebase-admin/app");
const { getFirestore } = require("firebase-admin/firestore");

initializeApp();

const db = getFirestore();

exports.getQuizById = onCall(async (context) => {
    const quizId = context.data.id;

    if (!quizId) {
        throw new HttpsError("invalid-argument", "调用函数时必须传入包含测验ID的参数\"id\"");
    }

    try {
        const quizDocRef = db.collection("quizzes").doc(quizId);
        const quizDoc = await quizDocRef.get();

        if (!quizDoc.exists) {
            throw new HttpsError("not-found", `ID为${quizId}的文档不存在,请验证ID后重试`);
        }

        return quizDoc.data();

    } catch (error) {
        logger.error("获取测验文档失败:", error);
        if (error instanceof HttpsError) {
            throw error;
        }
        throw new HttpsError("server-error", `服务器错误: ${error.message}`);
    }
});

客户端代码优化提示

当前客户端调用逻辑正确,建议替换硬编码ID为路由中获取的实际值:

import { Functions, httpsCallable } from '@angular/fire/functions';
import { ActivatedRoute } from '@angular/router';
import { inject } from '@angular/core';

private functions: Functions = inject(Functions);

constructor(private route: ActivatedRoute) {
  const id = this.route.snapshot.params['id'];
  const getQuizById = httpsCallable(this.functions, 'getQuizById');

  getQuizById({ id })
    .then((result) => {
      console.log('获取到的测验数据:', result.data);
    })
    .catch((error) => {
      console.error('调用函数失败:', error);
    });
}

错误日志说明

日志中Process exited with code 16是因为原函数访问了不存在的request.queryid,触发未捕获的运行时异常,修正参数获取逻辑后即可解决该问题。

内容的提问来源于stack exchange,提问作者Todd Davis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 22:23:31