node.js - 如何使用 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
}
}
问题是上下文变量在内部无法访问,我无法处理响应。无论执行失败或成功,上述方法的输出总是“完成”。
解决方案
您只能通过从函数声明中删除异步并在完成响应后使用 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();
}
});
}
推荐阅读
- c# - C# listview 子项未显示
- django - 需要登录会话 Selenium 的 Django 中的测试视图
- php - 如果两次上传相同的文件名,如何在laravel中显示错误消息
- python - 逻辑回归数据的完全分离
- php - 我在这个 foreach 循环中做错了什么?
- javascript - 将 props 传递给封装在 HOC 中的 React Redux 连接组件
- javascript - Vue.js - 在悬停时添加删除按钮并在按下按钮时删除它
- asp.net - 用户“SQLLogin”的 Asp.net LocalDB (SQL) 登录失败
- node.js - 使用 eventemitter 监听事件
- hive - Impala - 将 MON-YY 转换为 YYYYMM