【Serverless】云函数中调用云函数报错10602

【问题描述】

开发者希望在云函数代码中调用别的云函数,于是参考官方文档,编写Node.js的函数代码,导入到AGC控制台进行测试,返回结果总是会报下面这个错误。

{ "code": 180000, "message": "Call handler error: 10602: agc client name already exist" }

开发者的函数代码如下:

const agconnect = require('@agconnect/common-server');

const { AGCFunction } = require("@hw-agconnect/function-server");

let path = require('path');

let api_client_path = path.join(__dirname, "agc-apiclient.json");

const agcClient = agconnect.AGCClient.getInstance();

agconnect.AGCClient.initialize(agconnect.CredentialParser.toCredential(api_client_path));

var agcFunction = new AGCFunction(agcClient);

let myHandler = function(event, context, callback, logger) {

  let callable= agcFunction.wrap("gettman","$latest");

  let result=callable.call()

    //send response

    callback({"res":result});

};

module.exports.myHandler = myHandler;

 

【问题分析】

出现10602的错误一般是因为AGCClient在Node.js中初始化一次后不会清除缓存,在后续测试时会出现重复初始化的情况便会报AGCClient已存在的错误,所以在初始化前做个判断,如果存在AGCClient实例便不再初始化。做了判断后该代码还存在另外几个问题,也在下图标注了出来:

cke_5035.png

 

【解决方案】

如果要在云函数中调用云函数,需要注意以下几点:

1.测试函数时AGCClient实例需要判断是否已经存在,不存在则初始化。

2.var agcFunction = new AGCFunction(); 这个类传参应该是个字符串,或者为空,不能传agcClient对象

3.call()需要异步。

改进后的函数代码如下:

const agconnect = require('@agconnect/common-server');

const { AGCFunction } = require("@hw-agconnect/function-server");

let path = require('path');

let credentialPath = path.join(__dirname, 'agc-apiclient.json');

let credential = agconnect.CredentialParser.toCredential(credentialPath);

let agcClient;

try {

agcClient = agconnect.AGCClient.getInstance();

} catch {

agconnect.AGCClient.initialize(credential);

agcClient = agconnect.AGCClient.getInstance();

}

let myHandler = async function(event, context, callback, logger) {

var agcFunction = new AGCFunction();

let callable= agcFunction.wrap("test","$latest");

let result = callable.call({}).then(res => {

callback({"res":res});

}).catch(error => {

callback({"error":error});

});

};

module.exports.myHandler = myHandler;

 欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

posted @ 2023-04-27 09:50  华为开发者论坛  阅读(78)  评论(0编辑  收藏  举报