6.1: Handling Errors in Angular

We're going to use the HttpInterceptor to "catch" server-side errors.

Adding Interceptor

Add a new file to the src/app/services folder called error.interceptor.ts.

We'll also need to import Observable from the rxjs library:

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
],

Last updated