【发布时间】:2018-10-26 16:33:03
【问题描述】:
我目前正在试验使用 Google Firebase 函数来访问 Google API。它运行良好,但我在尝试管理可能检测到的错误时有点迷失......
在 .HTTPS getGoogleUsers 函数中,我想返回一个 HTTP 状态代码(200 或错误代码)和数据(或错误消息)
据我所见,我可以得到错误:
来自
connect()函数(500: Internal server error or 401 Unauthorized)来自
listUsers()函数(500: Internal server error or 400 Bad Request)
我完全或部分错了吗?在这种情况下我的策略应该是什么? 感谢您的反馈..
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const {google} = require('googleapis');
const KEY = require('./service-key.json');
// Create JSON Web Token Client
function connect () {
return new Promise((resolve, reject) => {
const jwtClient = new google.auth.JWT(
KEY.client_email,
null,
KEY.private_key,
['https://www.googleapis.com/auth/admin.directory.user'],
'adminuser@mydomain.com'
);
jwtClient.authorize((err) => {
if(err) {
reject(err);
} else {
resolve(jwtClient);
}
});
});
}
function listUsers (client) {
return new Promise((resolve, reject) => {
google.admin('directory_v1').users.list({
auth: client,
domain: 'mydomain.com',
}, (err, response) => {
if (err) {
reject(err);
}
resolve(response.data.users);
});
});
}
function getAllUsers () {
connect()
.then(client => {
return listUsers(client);
})
.catch(error => {
return error;
})
}
exports.getGoogleUsers = functions.https.onRequest((req, res) => {
const users = getAllUsers();
if (error) {
status = error.status;
data = error.message;
} else {
status = 200;
data = users;
}
res.send({ status: status, datas: data })
});
【问题讨论】:
-
部分
const users = getAllUsers(); if (error) { …不能工作 -
是的,我知道..这就是我要小费的原因...
-
你试过我下面的答案了吗?
-
是的,很抱歉我没有赶上 2 cmets ... 看看我的 ..
标签: javascript error-handling promise