我正在实现一个与 Firebase 集成的 Angular 应用程序,并尝试在用户使用不正确的凭据登录时处理错误:
@Injectable({
providedIn: 'root',
})
export class UserService {
constructor(private router: Router, private firebaseAuthService: AngularFireAuth) {
this.firebaseAuthService.setPersistence('session');
}
login(email: string, password: string) {
this.firebaseAuthService
.signInWithEmailAndPassword(email, password)
.then(() => this.router.navigateByUrl('foo'))
.catch(() => console.log('error handled'));
}
}
catch 方法成功“处理”了错误,但是,之后我仍然遇到未捕获的异常。
控制台输出:
已处理错误
错误FirebaseError:Firebase:没有 与该标识符对应的用户记录。用户可能已经 已删除。 (身份验证/未找到用户)。 在 createErrorInternal (index-e3d5d3f4.js:497:41) 在 _fail (index-e3d5d3f4.js:468:11) 在索引-e3d5d3f4.js:911:17 在 Generator.next() 处 在 asyncGeneratorStep (asyncToGenerator.js:3:1) 在 _next (asyncToGenerator.js:22:1) 在 _ZoneDelegate.invoke (zone.js:372:26) 在 Object.onInvoke (core.mjs:24210:33) 在 _ZoneDelegate.invoke (zone.js:371:52) 在 Zone.run (zone.js:134:43)
我尝试过以下方法:
所有这些方法最终都得到与上面提到的相同的结果(代码在 catch 块中运行,然后出现未捕获的异常)。
旁注:我在 SO 上发现了类似的问题(zone.js 承诺即使使用 catch 块也会返回未处理的承诺拒绝错误)和 Github(https://github.com/angular/angular/issues/31680)同样,它描述了相同的错误,并且 Github 问题中提到了一个 PR,但不幸的是没有解决问题。我已经尝试过 zoneJS 标志,但 PR 的唯一区别是错误现在已解开。
在您的 catch 块中,您将收到一个可以处理并采取操作的异常对象,在这种情况下,我已经构建和枚举来解释屏幕上的错误:
.catch(error =>{
this.material.toast(Errors[error.code], 3000, 'red full');
if(error.code === 'auth/user-not-found') this.router.navigateByUrl('login/register');
})