Skip to content

Commit

Permalink
Criando um interceptor para tratamento de erros
Browse files Browse the repository at this point in the history
  • Loading branch information
franciscolopes committed May 3, 2018
1 parent 78ff363 commit 45ad231
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
4 changes: 3 additions & 1 deletion src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { MyApp } from './app.component';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { CategoriaService } from '../services/domain/categoria.service';
import { ErrorInterceptorProvider } from '../interceptors/error-interceptor';

@NgModule({
declarations: [
Expand All @@ -26,7 +27,8 @@ import { CategoriaService } from '../services/domain/categoria.service';
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
CategoriaService
CategoriaService,
ErrorInterceptorProvider
]
})
export class AppModule {}
32 changes: 32 additions & 0 deletions src/interceptors/error-interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Rx'; // IMPORTANTE: IMPORT ATUALIZADO
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("Passou no interceptor");
return next.handle(req)
.catch((error, caught) => {

let errorObj = error;
if (errorObj.error) {
errorObj = errorObj.error;
}
if (!errorObj.status) {
errorObj = JSON.parse(errorObj);
}

console.log("Erro detectado pelo interceptor:");
console.log(errorObj);

return Observable.throw(errorObj);
}) as any;
}
}

export const ErrorInterceptorProvider = {
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true,
};
4 changes: 1 addition & 3 deletions src/pages/categorias/categorias.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ export class CategoriasPage {
.subscribe(response => {
this.items = response;
},
error => {
console.log(error);
});
error => {});
}

}

0 comments on commit 45ad231

Please sign in to comment.