Lỗi HTTP nên được xử lý ở đúng tầng: component/store xử lý lỗi nghiệp vụ cần hiển thị cụ thể; API service normalize response; interceptor xử lý cross-cutting concern như auth, retry, correlation id hoặc global error logging.
Ví dụ service trả fallback có kiểm soát:
loadUsers() {
return this.http.get<User[]>("/api/users").pipe(
retry({ count: 2, delay: 500 }),
catchError(error => {
this.logger.error(error)
return of([])
}),
)
}Không nuốt mọi lỗi ở interceptor vì component sẽ mất ngữ cảnh để hiển thị message đúng.
Handle HTTP errors at the right layer: component/store handles business errors that need specific UI; API services normalize responses; interceptors handle cross-cutting concerns such as auth, retry, correlation ids or global error logging.
Controlled fallback example in a service:
loadUsers() {
return this.http.get<User[]>("/api/users").pipe(
retry({ count: 2, delay: 500 }),
catchError(error => {
this.logger.error(error)
return of([])
}),
)
}Do not swallow every error in an interceptor because components lose the context needed to show the correct message.