我正在使用 React Native/Firebase/Redux 构建一个简单的登录系统。我正在尝试找出如何捕获由于登录尝试失败而发生的错误。
这是我的 authscreen.js:
const [alertShowing, setAlertShowing] = useState(false);
const [alertMessage, setAlertMessage] = useState('');
...
function handleLogin() {
const response = dispatch(login(email, password));
console.log(response);
}
actions.js:
export const login = (email, password) => {
return async (dispatch) => {
try {
const response = await Firebase.auth().signInWithEmailAndPassword(email, password);
dispatch(getUser(response.user.uid));
} catch (e) {
return e;
}
};
};
上面的 console.log(response) 正确地向我显示了错误消息,但这显然对用户来说不是很有用。另请注意,使用正确的凭据我可以正确登录。
我在
handleLogin()
中真正想做的是检查响应是否是错误,如果是,则 setlAlertShowing(true)
和 setAlertMessage
到我从 useDispatch 挂钩返回的内容,以便我可以很好地显示它给用户。
我该怎么办?短暂性脑缺血发作。
Firebase 错误消息是为开发人员设计的,对标准用户不友好。解决方案是识别身份验证错误代码并映射到用户友好的消息。
错误代码列表https://firebase.google.com/docs/auth/admin/errors
您可以使用这样的函数将 authError 映射到有意义的错误消息。
function mapAuthCodeToMessage(authCode) {
switch (authCode) {
case "auth/invalid-password":
return "Password provided is not corrected";
case "auth/invalid-email":
return "Email provided is invalid";
// Many more authCode mapping here...
default:
return "";
}
}
稍后使用
export const login = (email, password) => {
return async (dispatch) => {
try {
const response = await Firebase.auth().signInWithEmailAndPassword(email, password);
dispatch(getUser(response.user.uid));
} catch (e) {
dispatch({type:"authError",message:mapAuthCodeToMessage(e.code)}));
}
};
};
使用 substring 函数从错误中获取消息
auth()
error.message.substring(error.message.indexOf(']') + 2)