我使用代码来验证jwt中的是否过期(来自angular2-jwt)。
但是,如果用户更改localStorage中token的值,例如:
id_token =>“123”,它显示错误并停止应用。
但是,我想在Guard中处理此错误。
//错误:
core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: JWT must have 3 parts
Error: JWT must have 3 parts
如果引发了 throw ,如何在Guard中处理此错误?
//Guard.ts:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean
{
if (this.tokenService.isTokenExpired(token)) {
this.auth.loggedIn = false;
this.loginService.logout();
this.notifications.success = false;
this.notifications.status = 401;
this.notifications.state = 'alertFail';
this.notifications.message = 'Token Expirado! Faça o login novamente.';
this.notifications.arrayError = [];
this.notifications2.setNotifications(this.notifications);
this.router.navigate(['/login']);
return false;
}
return true;
}
//其中一个功能:
public decodeToken(token: string): any {
let parts = token.split('.');
if (parts.length !== 3) {
throw new Error('JWT must have 3 parts');
}
let decoded = this.urlBase64Decode(parts[1]);
if (!decoded) {
throw new Error('Cannot decode the token');
}
return JSON.parse(decoded);
}
最佳答案
try/catch块是您要执行的操作:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean
{
try {
if (this.tokenService.isTokenExpired(token)) {
this.auth.loggedIn = false;
this.loginService.logout();
this.notifications.success = false;
this.notifications.status = 401;
this.notifications.state = 'alertFail';
this.notifications.message = 'Token Expirado! Faça o login novamente.';
this.notifications.arrayError = [];
this.notifications2.setNotifications(this.notifications);
this.router.navigate(['/login']);
return false;
}
}
catch (e) {
return false;
}
return true;
}
关于angular - 从Angular 2/4中的正常函数处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45382041/