【问题标题】:Ignoring exception from a finished function in Cloud Functions忽略 Cloud Functions 中已完成函数的异常
【发布时间】:2018-06-25 14:01:18
【问题描述】:

我正在使用 Cloud Functions for Firebase 使用 this 获取访问令牌,之后我正在对 https://www.googleapis.com/auth/cloud-platform 进行休息调用。但是在这样做的同时,我得到了异常 Ignoring exception from a finished function。

我想知道为什么我会收到此消息以及其背后的原因是什么。 #AskFirebase

已编辑 下面是我的 accessTokenHandler.js

 const functions = require('firebase-functions');
 var googleAuth = require('google-oauth-jwt');
 const predictor=require("../prediction/predictor");


module.exports.getAccessToken=() =>{

googleAuth.authenticate({
email: 'my.gserviceaccount.com',
keyFile: "./accesstoken/key2.pem",
expiration: 3600000,
scopes: ['https://www.googleapis.com/auth/cloud-platform']
}, function (err, token) {
if(token){
    console.log("token:"+token);
    predictor.predict(token);
}
 if(err)console.log("err:"+err);
});
}

下面是我的 predictor.js

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

module.exports.predict=(accessToken) =>{
predictImage(accessToken);
}

function predictImage(accessToken){

var httpRequest= new XMLHttpRequest();
httpRequest.open("POST","url",true);
httpRequest.setRequestHeader("Content-Type","application/json");
httpRequest.setRequestHeader("Accept","application/json");
httpRequest.setRequestHeader("Authorization", "Bearer " + accessToken); 
httpRequest.send(getRequestJson());

httpRequest.onreadystatechange =function(){
    if(this.readyState==4){
    console.log("status:"+this.status+" state:"+this.readyState)
    console.log("response:"+this.responseText)
    }
}
}

function getRequestJson()
{
var b64Image='/9j/oAxt--encoded---f/2Q==';
var requestJson={"instances":
[{"key":"input_cloudfunction.jpg","image_bytes":{"b64":b64Image}}]};
return requestJson;
}

还有我的 index.js 文件

const functions = require('firebase-functions');

exports.handleFreshAccessToken = functions.https.onRequest((request, response) => {
 response.send("Hello from Firebase!"); 
 const accessHandler=require("./accesstoken/accesstoken_handler");
 return accessHandler.getAccessToken();
});

【问题讨论】:

  • 请显示您的函数的代码。
  • @DougStevenson 看到我用代码编辑了我的问题
  • 产生错误的函数名称以“handleFresh”开头,但我在您提供的代码中没有看到名为该名称的云函数。
  • 是的,因为它是 index.js .... 让我也提供给你
  • 看看我已经添加了我的 index.js 代码

标签: node.js firebase google-cloud-functions


【解决方案1】:

显然,来自异步函数的未捕获异常是 Cloud Functions 框架中的 not displayed。 解决方案是用try {} catch 块包围代码,await 用于异步代码,并在 catch 块中记录所有异常。

例如:

async function ()
{
    try
    {
        // throws exception
        await SomeFunc ()
    }
    catch (e)
    {
        console.log ('error: ' + e)
    }
}

【讨论】:

    【解决方案2】:

    您的代码在完成之前发生了一些错误。对于 HTTPS 类型的函数,它们在向客户端发送响应时正式结束。在您的代码中,您立即向客户端发送响应,这意味着您在此之后所做的所有其他事情都发生在“函数完成后”。

    如果你在函数中有异步工作要做,你应该在发送响应之前等待所有这些完成(使用承诺)。

    【讨论】:

    • 后台函数怎么样,如何知道异常细节?
    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2023-04-10
    • 2020-09-11
    相关资源
    最近更新 更多