在Angular中处理来自正常函数的错误2/4
问题描述:
我使用代码来验证jwt是否已过期(来自angular2-jwt)。 但是,如果用户更改localStorage中令牌的值,例如: id_token =>“123”,它会显示错误并停止应用程序。 但我想在Guard中处理这个错误。在Angular中处理来自正常函数的错误2/4
//错误:
core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: JWT must have 3 parts
Error: JWT must have 3 parts
我如何处理在后卫这个错误,如果掷被激发?
//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;
}
我猜我对你试图完成的事情感到困惑。警卫不能正常工作吗? 老实说,验证令牌的最好方法是将其发送回可以通过并通过验证的API。如果您的应用可以解码令牌,那么您已经失去了使用令牌验证身份的任何安全性。 – joshrathke