0

我正在关注文档中的示例

ref.authWithCustomToken(authToken, function(error, authData) {
  if (error) {
    console.log("Authentication Failed!", error);
  } else {
    console.log("Authenticated successfully with payload:", authData);
  }
});

如果我将无效令牌传递给 authWithCustomToken(例如 authToken 未定义),它会引发错误,而不是将错误代码传递给回调。换句话说,两者都没有console.log被执行,但是会抛出这个错误:

First argument must be a valid credential (a string).

将它包装起来try catch很容易解决问题,但我没有在文档中看到任何提及。这是预期的行为吗?

在我的用例中,令牌是通过 url 传递的,因此未定义的参数是可能的错误情况。

4

1 回答 1

0

来自 firebase-debug.js:

if (!goog.isString(cred)) {
   throw new Error(fb.util.validation.errorPrefix(fnName, argumentNumber, optional) + "must be a valid credential (a string).");
}

可能发生了什么:
您传递了一个非字符串值,authToken因此错误没有发生在 Firebase(服务器)端,它发生在客户端(您的端),因此不会在回调函数中报告,而是作为 Javascript 异常你的代码。

可能的解决方法(我不知道为什么,但如果你愿意的话)
如果你想传递一个变量authToken并且它不能是一个字符串,你仍然想得到“错误的凭据”错误,而不是类型验证,那么您需要使用以下命令强制进行字符串转换:

var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
var numberAuthToken = 212312312312312; // number
var stringAuthToken = String(numberAuthToken);
ref.authWithCustomToken(stringAuthToken, function(error, authData) {
  if (error) {
    console.log("Authentication Failed!", error);
  } else {
    console.log("Authenticated successfully with payload:", authData);
  }
});

但这对我来说没有意义。:)

于 2015-07-10T17:35:20.407 回答