Câu hỏi phỏng vấn Angular
Câu hỏi

How do you perform Error Handling for HttpClient ?

Câu trả lời

Error handling for HttpClient in Angular is a critical aspect of developing a robust application. Angular provides several mechanisms to handle errors when making HTTP requests. Here's a comprehensive approach to managing errors with HttpClient:

Using catchError and throwError with RxJS Operators

The primary method for handling errors in Angular is by using the HttpClient service in conjunction with RxJS operators like throwError and catchError. When an HTTP request is made and an error occurs, the error is wrapped in an HttpErrorResponse object. This object can be caught and processed using the catchError operator within the RxJS pipe method.

Here's an example of how to use catchError:

typescript Copy
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

constructor(private http: HttpClient) {}

getData() {
  return this.http.get('/api/data').pipe(
    catchError((error: HttpErrorResponse) => {
      // Handle the error here
      // Can check the error status code and respond accordingly
      return throwError(() => error); // Rethrow the error
    })
  );
}

Global Error Handling with HttpInterceptor

For global error handling, Angular provides the HttpInterceptor interface, which allows you to intercept HTTP requests and responses and handle errors or modify the request/response globally. This is useful for handling common error scenarios across the entire application.

Here's a basic example of an interceptor that handles errors:

typescript Copy
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        // Global error handling logic
        // Can log the error or display a notification
        return throwError(() => error);
      })
    );
  }
}

Handling Errors Locally in Components or Services

Errors can also be handled locally within components or services. This allows for more specific error ...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

Do I need to bootstrap custom elements?

middle

What is the option to choose between Inline and External template file?

middle

What is Protractor?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào