# HTTP Interceptors & Error Handling — Angular Fundamentals: Components, Signals and Routing

Source: https://www.geekswithgeeks.com/en/angular/ng-http-interceptors

> Add auth headers, logging and global error handling to every request with functional HTTP interceptors.

## A functional interceptor

A functional interceptor is a function that can clone and modify each request before it is sent, and handle the response or error.

```typescript
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { catchError, throwError } from 'rxjs';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();
  const authReq = token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
  return next(authReq).pipe(
    catchError((err) => {
      if (err.status === 401) inject(AuthService).logout();
      return throwError(() => err);
    }),
  );
};
```

## Register it

Add interceptors when providing `HttpClient`.

```typescript
bootstrapApplication(AppComponent, {
  providers: [provideHttpClient(withInterceptors([authInterceptor]))],
});
```

Interceptors run in the order listed. Keep each one focused, and never log tokens or personal data.
