如何通过程序了解Mongo Realm中的错误登录



我登录时得到了这个,问题是无法知道失败的原因,我需要向UI显示信息或知道我面临的问题类型。Doc对错误只字未提。

try {
const user = await realmApp.logIn(credentials);
console.log('signed in', user);
} catch (e) {
console.log(e);
}

打印出来:

Error: Request failed (POST https://stitch.mongodb.com/api/client/v2.0/app/xxxx/auth/providers/local-userpass/login): invalid username/password (status 401)
at Function.fromRequestAndResponse (bundle.dom.es.js:2696)
at async Fetcher.fetch (bundle.dom.es.js:2864)
at async Fetcher.fetchJSON (bundle.dom.es.js:2881)
at async Authenticator.authenticate (bundle.dom.es.js:2592)
at async App.logIn (bundle.dom.es.js:3073)
at async handleSignIn (SignIn.js:37)

从程序上讲,我希望一个带有error_code的对象能够对不同的情况做出反应,例如错误的密码/用户名或等待的电子邮件确认。

我也试着不使用async,但它给出了相同的输出。。。

const handleSignIn = event => {
event.preventDefault();
setLoading(true);
const credentials = Realm.Credentials.emailPassword(email, password);
realmApp.logIn(credentials)
.then(user => console.log(user))
.catch(e => console.log(e));
setLoading(false);
};

还尝试了异常道具e.message和e.name:

e.message:

Request failed (POST https://stitch.mongodb.com/api/client/v2.0/app/xxx/auth/providers/local-userpass/login): invalid username/password (status 401)

e.name

Error

我创建了一个小的CodeSandbox,演示如何从错误对象中获取各个属性:https://codesandbox.io/s/realm-web-error-codes-2oei2?file=/src/App.tsx

import React, { useCallback, useState } from "react";
import { getApp, Credentials, MongoDBRealmError } from "realm-web";
const app = getApp("realmjstestapp-jjhtf");
export default function App() {
const [error, setError] = useState<MongoDBRealmError | null>(null);
const handleClick = useCallback(() => {
const invalidCredentials = Credentials.jwt("whatever");
app.logIn(invalidCredentials).then(() => {
console.log("That was unexpected ...");
}, setError);
}, [setError]);
return (
<div>
<h1>Realm Web Error codes</h1>
<button onClick={handleClick}>Make an error!</button>
{error ? (
<dl>
<dt>Combined error message:</dt>
<dd>{error.message}</dd>
<dt>Error message:</dt>
<dd>{error.error}</dd>
<dt>URL fetched:</dt>
<dd>{error.url}</dd>
<dt>Method used when fetching:</dt>
<dd>{error.method}</dd>
<dt>Error code:</dt>
<dd>{error.errorCode}</dd>
<dt>Status code:</dt>
<dd>{error.statusCode}</dd>
<dt>Status text:</dt>
<dd>{error.statusText}</dd>
</dl>
) : (
<h2>Click above ..</h2>
)}
</div>
);
}

所有javascript错误代码都封装在一个名为ErrorCodes的枚举中,它们可以在错误代码git 中找到

它们也记录在RealmError类中,该类扩展了Error类(e(,以便您可以将其与可用错误进行比较

这也允许访问序列化的ErrorCode

我的javascript很生疏,但你不能做这样的事情吗?

try {
do something with realm
} catch (RealmError e) {
if (e.getMessage().contains("Permission denied")) {
do something because of the error
} else {
throw e;
}
}

或将e.equals与枚举一起使用,e.description用于其他信息等

查看这是否适用于

realmApp.login(credentials).then(data=>{
user = data ; 
}).error(err=>{console.log(err)})
}

确保从函数中删除async

最新更新