# HTTP Interceptors और Error Handling — Angular Fundamentals: Components, Signals और Routing

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

> Functional HTTP interceptors से हर request में auth headers, logging और global error handling जोड़ें।

## Functional interceptor

Functional interceptor एक function है जो हर request भेजने से पहले उसे clone व modify कर सकता है और response या 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 करें

`HttpClient` provide करते समय interceptors जोड़ें।

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

Interceptors सूचीबद्ध क्रम में चलते हैं। हर एक को केंद्रित रखें, और tokens या निजी data कभी log न करें।
