पाठ 22 / 32
HTTP Interceptors और Error Handling
Functional HTTP interceptors से हर request में auth headers, logging और global error handling जोड़ें।
लेखक: Rahul Agarwal · 15 साल से वेब डेवलपर · अपडेट: 1 अक्टू॰ 2026
Functional interceptor
Functional interceptor एक function है जो हर request भेजने से पहले उसे clone व modify कर सकता है और response या error संभाल सकता है।
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 जोड़ें।
bootstrapApplication(AppComponent, {
providers: [provideHttpClient(withInterceptors([authInterceptor]))],
});Interceptors सूचीबद्ध क्रम में चलते हैं। हर एक को केंद्रित रखें, और tokens या निजी data कभी log न करें।