import { Observable } from "rxjs/Rx"
// ...
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).catch(error => {
if (error instanceof HttpErrorResponse) {
if (error instanceof HttpErrorResponse) {
const applicationError = error.headers.get('Application-Error');
if (applicationError) {
return Observable.throw(applicationError);
}
const serverError = error.error;
let modelStateErrors = '';
if (serverError && typeof serverError === 'object') {
for (const key in serverError) {
if (serverError[key]) {
modelStateErrors += serverError[key] + '\n';
}
}
}
return Observable.throw(
modelStateErrors || serverError || 'Server error'
);
}
}
})
}
}
export const ErrorInterceptorProvider = {
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true
};
Now, make sure to import it into app.module.ts and add it to the providers array:
import { ErrorInterceptorProvider } from './services/error.interceptor';
// ...
providers: [
AuthService,
UserService,
AuthGuard,
MemberDetailResolver,
MemberListResolver,
ErrorInterceptorProvider
],