Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

javascript - Status 500 "Error: Could not handle the request" for every other request

I have made a Flutter app and just started using Cloud Functions to send push notifications to other phones. I got the Cloud Function to work by calling it with an API call, that is, the message is sent and I get the response code 200. But funnily enough, about every other time or so (sometimes more, sometimes less) I get the response:

Status code: 500, body: "Error: Could not handle the request"

This is especially weird, since at the moment, I'm sending the exact same message every time!... As in, it's the exact same API call with no header and the exact same body. Yet, I get different results. What could the problem be?

Here's my Cloud Function:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

exports.sendMsg = functions.https.onRequest((request, response) => {

  var decodedBody = JSON.parse(request.body);
  const message = decodedBody;

  // Send a message to the device corresponding to the provided
  // registration token:
  admin.initializeApp();
  admin.messaging().send(message)
      .then((res) => {
        // Response is a message ID string.
        console.log("Successfully sent message:", res);
        response.send("Message sent!

" + res);
      })
      .catch((error) => {
        console.log("Error sending message:", error);
        response.send("Error sending message:

" + error);
      });
});

And this is my API call:

import 'dart:convert';
import 'my_firebase.dart';
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';

//...//
void msgFunction(){
  final FirebaseMessaging _fcm = FirebaseMessaging();
         await MyFirebase.myFutureFirebaseApp;
          String fcmToken = await _fcm.getToken();
          http.Response res;

          try {
            res = await http.post(
              'https://us-central1-<my_project>.cloudfunctions.net/sendMsg',
              body: jsonEncode({
                "notification": {
                  "title": "This is my title",
                  "body": "Accept Ride Request",
                },
                "data": {
                  "score": "850",
                  "time": "245",
                  "click_action": "FLUTTER_NOTIFICATION_CLICK",
                  "id": "1",
                  "status": "done",
                },
                "token": "$fcmToken",
              }
              ),
            );
          } catch (e) {
            print('Caught an error in API call!');
            print('e is: ${e.toString()}');
            if (res != null) print('Status code in apiCall() catch is ${res.statusCode}');
          }
}

The online function logs of an execution that fails:

Function execution started
Function execution took 173 ms, finished with status: 'crash'
question from:https://stackoverflow.com/questions/66064282/status-500-error-could-not-handle-the-request-for-every-other-request

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solved it, myself! ??

The problem was apparently the admin.initializeApp(); command, which I kind of suspected... because at some point, the logs told me this function was called twice.

And the solution was to put it outside the Cloud Function, rather than inside it! Like this:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.sendMsg = functions.https.onRequest((request, response) => {

  var decodedBody = JSON.parse(request.body);
  const message = decodedBody;

  // Send a message to the device corresponding to the provided
  // registration token:
  admin.messaging().send(message)
      .then((res) => {
        // Response is a message ID string.
        console.log("Successfully sent message:", res);
        response.send("Message sent!

" + res);
      })
      .catch((error) => {
        console.log("Error sending message:", error);
        response.send("Error sending message:

" + error);
      });
});

It was video no. 2 in this video series tutorial on Cloud Functions from Firebase that made me figure it out:

https://firebase.google.com/docs/functions/video-series

It's a good series! I can recommend it.

Peace! ??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...