我使用代码验证jwt是否已过期(来自angular2-jwt)。 但是如果用户在localStorage中更改令牌的值,则ex: id_token => “123”,它显示错误并停止应用程序。 但是,我想在Guard中处理这个错误。
//错误:
var PreDefinedTasks = ["1", "2", "3", "4"]
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
if cell.accessoryType == .checkmark{
cell.accessoryType = .none
}
else{
cell.accessoryType = .checkmark
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return PreDefinedTasks.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "List1", for: indexPath)
cell.textLabel?.text = PreDefinedTasks[indexPath.row]
return cell
}
如果抛出throw会如何在Guard中处理此错误?
// Guard.ts:
core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: JWT must have 3 parts
Error: JWT must have 3 parts
//其中一项功能:
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;
}
答案 0 :(得分:0)
你正在尝试使用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;
}