Angular API Error Handling with Interceptors

Day7/30 || Angular 👉 “Stop writing API error handling in every Angular service 👇” Handling API errors in every Angular service… is one of the most repetitive things ever 👇 I worked on a project where every API call had: • try/catch logic • error handling • token checks 👉 Result? Duplicate code everywhere 😬 ⸻ 💡 Here’s what helped: HTTP Interceptors Instead of handling errors in every service, handle them centrally. ✅ Create an Interceptor Typescript: @Injectable() export class ErrorInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler) { return next.handle(req).pipe( catchError((error: HttpErrorResponse) => { console.error('API Error:', error.message); return throwError(() => error); }) ); } } ✅ Register it Typescript: providers: [ { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true } ] ✅ What this solves: • Centralized error handling • Cleaner services • Better maintainability ⸻ ⚡ Bonus: You can also use interceptors for: • Adding auth tokens 🔐 • Logging requests • Showing loaders globally ⸻ 🚀 Real impact: Reduced duplicate code + consistent error handling across the app ⸻ 👉 Takeaway: If you’re handling API logic in every service… you’re missing the power of interceptors. ⸻ Are you using interceptors just for auth or for error handling too? 🤔 #Angular #FrontendDevelopment #API #JavaScript #SoftwareEngineering

👉 Interceptors helped me clean up a lot of repeated API logic in one of my projects.

Like
Reply

To view or add a comment, sign in

Explore content categories