Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
- import {Injectable} from '@angular/core';
- import {AuthService} from '@services/auth.service';
- import {Events} from '@services/events';
- import {ToastrService} from 'ngx-toastr';
- import {Observable, throwError} from 'rxjs';
- import {catchError} from 'rxjs/operators';
- @Injectable()
- export class ErrorInterceptor implements HttpInterceptor {
- constructor(
- private authenticationService: AuthService,
- private toastr: ToastrService,
- public events: Events
- ) {
- }
- intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
- return next.handle(request).pipe(catchError(err => {
- let pathname = window.location.pathname;
- if (!pathname.includes('/login')) {
- if ([401, 403].indexOf(err.status) !== -1) {
- if (err.code && [202].indexOf(err.code) !== -1 || err.status === 401) {
- this.toastr.info('Token do usuário expirou, realize o login novamente.');
- this.authenticationService.logout();
- location.reload();
- } else {
- this.toastr.error('Usuário não possui permissão para executar esta ação.');
- }
- }
- if ([500].indexOf(err.status) !== -1) {
- this.events.broadcast('onSpinnerDisabled');
- this.toastr.error('Tivemos um problema ao se comunicar com nossos serviços, tente novamente mais tarde.');
- }
- if ([400].indexOf(err.status) !== -1 && !pathname.includes('/login')) {
- if (err.error && err.error.errors) {
- for (const error in err.error.errors) {
- this.toastr.error(err.error.errors[error], 'Verifique os campo', {closeButton: true, timeOut: 5000});
- }
- } else {
- let codeError: string = err.error.codigo !== 0 ? `${err.error.codigo}`.padStart(3, '0') : '';
- let messageError: string = err.error.message !== undefined ? err.error.message : '';
- if (!codeError.startsWith('')) messageError = `${codeError} - ${messageError}`
- this.toastr.warning(messageError);
- }
- }
- }
- // TODO - será tratado aqui posteriormente em caso de token expirado o refresh token
- return throwError(err);
- }))
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement