angular - 从Angular 2/4中的正常函数处理错误

标签 angular error-handling

我使用代码来验证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/

相关文章:

node.js - 如何每次都引用本地安装的Angular2包而不是 "npm install"?

angular - Ionic 3 - 标签 href 内部链接

python - "takes 1 positional argument but 2 were given"同时找到函数的最小值

asp.net-mvc - 404.20异常未被ASP.net Core捕获

python - Python –没有错误但也没有返回数据

java - eclipse更新时出错

angular - 来自 Angular 4 的 HttpInterceptor 单元测试

d3.js - 将 D3 与 Angular-cli 集成

linux - E2E测试失败错误: cannot find chrome binary in Linux

node.js - NodeJS Mongoose Schema 'save' 函数错误处理?