[英]Better error handling with Promises?
我目前正在嘗試使用Google Firebase函數來訪問Google API。 它運行良好,但是我在嘗試管理可以檢測到的錯誤時有點迷路了...
在.HTTPS getGoogleUsers
函數中,我想返回一個HTTP狀態代碼(200或錯誤代碼)和數據(或錯誤消息)
據我所見,我會得到錯誤:
從connect()
函數(500:內部服務器錯誤或401未經授權)
從listUsers()
函數(500:內部服務器錯誤或400錯誤的請求)
我是全部還是部分錯誤? 在這種情況下,我應該采取什么策略? 感謝您的反饋..
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 })
});
我想你在找
function getAllUsers () {
return connect().then(listUsers);
//^^^^^^
}
exports.getGoogleUsers = functions.https.onRequest((req, res) => {
getAllUsers().then(users => {
return {status: 200, datas: users};
}, error => {
return {status: error.status, datas: error.message};
}).then(response => {
res.send(response);
});
});
它使用.then(…, …)
方法和兩個回調來區分成功和錯誤情況,並等待promise的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.