【问题标题】:Better error handling with Promises?使用 Promises 更好地处理错误?
【发布时间】: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


【解决方案1】:

我想你正在寻找

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);
  });
});

这使用the .then(…, …) method with two callbacks来区分成功和错误的情况,并等待promise的结果。

【讨论】:

  • 是的,好点..但是我在 libe 中收到一个 lint 错误:getAllUsers().then(users => {... 53:3 error Expected catch() or return promise/catch-或返回
  • 如果三个回调中的任何一个(尤其是res.send)抛出错误,都会导致未处理的拒绝。如果需要,您可以在末尾添加另一个 .catch(console.error)
猜你喜欢
  • 2017-01-11
  • 2016-11-05
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多