我正在使用Cloud Functions for Firebase来使用this获取访问令牌,之后我正在对https://www.googleapis.com/auth/cloud-platform进行休息调用。但是在这样做的过程中,我得到了异常,忽略了已完成函数的异常。
我想知道为什么我收到这条消息,背后的原因是什么。 #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);
});
}
以下是我的预测器.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();
});
答案 0 :(得分:5)
在代码完成之前,代码中发生了一些错误。对于HTTPS类型函数,它们在响应发送到客户端时正式完成。在您的代码中,您将立即向客户端发送响应,这意味着在“功能完成后”发生之后您正在执行的所有其他操作。
如果你在函数中有异步工作,你应该在发送响应之前等待所有这些(使用promises)。
答案 1 :(得分:0)
在Cloud Functions框架中,显然not displayed是来自异步函数的未捕获异常。
解决方案是用try {} catch
块包围代码,用await
包围异步代码,并将所有异常记录在catch块中。
例如:
async function ()
{
try
{
// throws exception
await SomeFunc ()
}
catch (e)
{
console.log ('error: ' + e)
}
}