Advertisement
deoprog

error interceptor

Dec 24th, 2020
1,089
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
  2. import {Injectable} from '@angular/core';
  3. import {AuthService} from '@services/auth.service';
  4. import {Events} from '@services/events';
  5.  
  6. import {ToastrService} from 'ngx-toastr';
  7. import {Observable, throwError} from 'rxjs';
  8. import {catchError} from 'rxjs/operators';
  9.  
  10. @Injectable()
  11. export class ErrorInterceptor implements HttpInterceptor {
  12.   constructor(
  13.     private authenticationService: AuthService,
  14.     private toastr: ToastrService,
  15.     public events: Events
  16.   ) {
  17.   }
  18.  
  19.   intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  20.     return next.handle(request).pipe(catchError(err => {
  21.  
  22.       let pathname = window.location.pathname;
  23.  
  24.       if (!pathname.includes('/login')) {
  25.         if ([401, 403].indexOf(err.status) !== -1) {
  26.           if (err.code && [202].indexOf(err.code) !== -1 || err.status === 401) {
  27.             this.toastr.info('Token do usuário expirou, realize o login novamente.');
  28.             this.authenticationService.logout();
  29.             location.reload();
  30.           } else {
  31.             this.toastr.error('Usuário não possui permissão para executar esta ação.');
  32.           }
  33.         }
  34.  
  35.         if ([500].indexOf(err.status) !== -1) {
  36.           this.events.broadcast('onSpinnerDisabled');
  37.           this.toastr.error('Tivemos um problema ao se comunicar com nossos serviços, tente novamente mais tarde.');
  38.         }
  39.  
  40.         if ([400].indexOf(err.status) !== -1 && !pathname.includes('/login')) {
  41.           if (err.error && err.error.errors) {
  42.             for (const error in err.error.errors) {
  43.               this.toastr.error(err.error.errors[error], 'Verifique os campo', {closeButton: true, timeOut: 5000});
  44.             }
  45.           } else {
  46.             let codeError: string = err.error.codigo !== 0 ? `${err.error.codigo}`.padStart(3, '0') : '';
  47.             let messageError: string = err.error.message !== undefined ? err.error.message : '';
  48.             if (!codeError.startsWith('')) messageError = `${codeError} - ${messageError}`
  49.             this.toastr.warning(messageError);
  50.           }
  51.         }
  52.       }
  53.  
  54.       // TODO - será tratado aqui posteriormente em caso de token expirado o refresh token
  55.  
  56.       return throwError(err);
  57.     }))
  58.   }
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement