M
M
Maxim Tarabrin2017-07-13 10:31:06
JavaScript
Maxim Tarabrin, 2017-07-13 10:31:06

How to handle errors from the server?

I am learning angular, writing applications that could communicate with the server. Authentication occurs through a JWT token. For example, the situation is now, I send a request to the server to check the validity of the token. In response, I receive an answer, from which I pulled out an error somehow. But at the end, when throwing and returning an observable, the error additionally falls out. Obviously, I'm not handling the error correctly. Tell me the guru of angular and javascript.
authService

export class AuthService {
  backendUrl = "http://127.0.0.1:8000/";
  constructor(private http: Http,
              private router: Router) { }

  verifyToken(token: string): Observable<{}>{
    let urlVerify = 'api-token-verify'
    let headers = new Headers({'Content-Type':'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this.backendUrl+'api-token-verify/', {token}, options)
      .map((response: Response) => response.json())
      .catch((error: Response) => this.handleError(error));
  }

  authLogin(login: string, password: string){
    let urlLogin = 'api/v1/auth/login';
    let headers = new Headers({'Content-Type':'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this.backendUrl+urlLogin, {username: login, password: password}, options)
      .map((response: Response) => response.json())
      .catch(this.handleError);
  }

  handleError(error: any){
    this.router.navigate(['/login']);
    let err_array = error.json()
    return Observable.throw(err_array['non_field_errors']);
  }
}

authenticationGuard
export class AuthenticationGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router){
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      if(localStorage.getItem('Token')){
        let token = localStorage.getItem('Token');
        return this.authService.verifyToken(token).map(res => {
          if(res['token'] === token){
            return true;
          }
          console.log(res);
          return false;
        });
      }else{
        this.router.navigate(['/login']);
        return false;
      }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aleksei Podgaev, 2017-07-13
@alexiusp

You are not confused by two calls this.router.navigate(['/login']);in two places?
Why are you catching errors in the authorization service? If the router itself should monitor this, let it monitor it. Put interception and error handling there, and remove it from the service.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question