Menu

Creating a HTTP_INTERCEPTORS in Angular to catch any server 500 or unhanded errors

It’s been a while I have done a blog post, a lot changed.

Normally I have a base service class for 5XXX server errors or unhandled exceptions, or even in a case where you have a 422 /400 where there is a validation error and you want to warn the end-user to double-check the form inputs.

This is another way to globally handle error messages.

First, you need to implement the HTTP interceptor (HTTP_INTERCEPTORS)

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
// @ts-ignore
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor() { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
      .pipe(
        catchError((error: HttpErrorResponse) => {
          if (error.status === 500) {
            // you can bring a fancy model dialog for this.
            alert('Your request could not be processed. Please try again, or contact XXXXX for assistance.')
          }
          return throwError(error);
        })
      );
  }  
}

once you have that in place you can register the HTTP interceptor on app.module.ts like below.

import ......
import ......
import { HttpErrorInterceptor } from './shared/utils/http.error.interceptor';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    ......,
    .....
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpErrorInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

Neat solution !!! ? ping me back if you find it interesting

Leave a comment