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

419

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!\n\n" + res);
      })
      .catch((error) => {
        console.log("Error sending message:", error);
        response.send("Error sending message:\n\n" + 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! ✌️

Share:
419
Karolina Hagegård
Author by

Karolina Hagegård

Updated on December 27, 2022

Comments

  • Karolina Hagegård
    Karolina Hagegård over 1 year

    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!\n\n" + res);
          })
          .catch((error) => {
            console.log("Error sending message:", error);
            response.send("Error sending message:\n\n" + 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'