首页 > 解决方案 > 如何使用 Nodejs 处理具有 ms-rest-azure 的函数应用程序中的异常

问题描述

我在 azure 门户中创建了一个函数应用程序,将 v12 的 Nodejs 作为运行时环境。

我可以使用服务主体名称和密码登录,如下所示:

module.exports = async function (context, req) {
    context.log("Started Execution");
    msRestAzure.loginWithServicePrincipalSecret(clientId, secret, domain, function(err, credentials) {
       if (err) return console.log(err);
       var client = new someAzureServiceClient(credentials, 'subscriptionId');

       if(req.body.action ==="xyz") {
         client.someOperationGroup.method(param1, param2, function(err, result) {
           if (err) {
             context.res = {
               status: 500,
               body: "Error: " + err
             }
           }
           context.res = {
             status: 200,
             body: "action executed" + result
           }
         });
       }
       else {
         context.res = {
           status: 500,
           body: "failed"
         }
       }
     });
     context.res = {
       status: 200,
       body: "Done" // Output
     }
}

问题是上下文变量在内部无法访问,我无法处理响应。无论执行失败或成功,上述方法的输出总是“完成”。

标签: node.jsazureazure-function-app

解决方案


您只能通过从函数声明中删除异步并在完成响应后使用 context.done() 来访问其他调用中的上下文变量。更改后您的代码将如下所示。

module.exports = function (context, req) {
context.log("Started Execution");
msRestAzure.loginWithServicePrincipalSecret(clientId, secret, domain, function(err, credentials) {

   context.log("===Here you are able to access context under this call=====");

   if (err) return console.log(err);
   var client = new someAzureServiceClient(credentials, 'subscriptionId');

   if(req.body.action ==="xyz") {
     client.someOperationGroup.method(param1, param2, function(err, result) {
       if (err) {
         context.res = {
           status: 500,
           body: "Error: " + err
         }
       } else {
           context.res = {
             status: 200,
             body: "action executed" + result
           }
        }
        context.done();
     });
   } else {
     context.res = {
       status: 500,
       body: "failed"
     }
     context.done();
   }
 });
}

推荐阅读