Best way to handle HTTPErrorResponse with Angular 7

Discussão em 'Angular' iniciado por bhavs, Outubro 23, 2024.

  1. bhavs

    bhavs Guest

    So the backend Server returns different status code and HttpErrorResponse when there are erroneous requests from the front end; I have realised the best way to manage this is using interceptors in an Ionic 4/Angular 7 setup.

    I have tried interceptors a couple of times and I am stuck with different issues. I am now following the steps in this link

    My services are defined like this :

    saveLocationNew(request: AddLocationRequest, entityId:string, userId:string): Observable<AddLocationResponse> {

    return this.httpClient.post<AddLocationResponse>(this.addLocationUrl, request , {headers:Constants.getHeaders(userId,entityId)})
    }


    With the interceptors it is now :

    saveLocationNew(request: AddLocationRequest, entityId:string, userId:string): Observable<AddLocationResponse> {

    return this.httpClient.post<AddLocationResponse>(this.addLocationUrl, request , {headers:Constants.getHeaders(userId,entityId)})
    .pipe(
    tap(_ => console.log('creating a new location')),
    catchError(this.handleError('new Location',[]))
    );
    }


    The issue being my existing service returns a response of type of AddLocationResponse; but in case of error how do I define the type of the return object and ionic serve also throws this error :

    ERROR in src/app/services/location.service.ts(42,11): error TS2322: Type 'Observable<any[] | AddLocationResponse>' is not assignable to type 'Observable<AddLocationResponse>'.
    [ng] Type 'any[] | AddLocationResponse' is not assignable to type 'AddLocationResponse'.
    [ng] Type 'any[]' is not assignable to type 'AddLocationResponse'.
    [ng] Property 'name' is missing in type 'any[]'.
    [ng] src/app/services/location.service.ts(74,49): error TS2339: Property 'message' does not exist on type 'T'.


    Any idea what would be the best way to implement interceptors so that the component(*.page.ts files) won't need any change .


    My interceptor looks like this :

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const token = localStorage.getItem('token');

    if (token) {
    request = request.clone({
    setHeaders: {
    'Authorization': token
    }
    });
    }

    if (!request.headers.has('Content-Type')) {
    request = request.clone({
    setHeaders: {
    'content-type': 'application/json'
    }
    });
    }

    request = request.clone({
    headers: request.headers.set('Accept', 'application/json')
    });

    return next.handle(request).pipe(
    map((event: HttpEvent<any>) => {
    if (event instanceof HttpResponse) {
    console.log('event--->>>', event);
    }
    return event;
    }),
    catchError((error: HttpErrorResponse) => {
    if (error.status === 401) {
    if (error.error.success === false) {
    this.presentToast('Login failed');
    } else {
    console.log(' route this to right place');
    // this.router.navigate(['auth/login']);
    }
    }
    if (error.status === 500) {
    if (error.error.success === false) {
    this.presentToast('Something went wrong, Please contact Administrator');
    } else {
    console.log(' route this to right place');
    // this.router.navigate(['auth/login']);
    }
    }
    //431

    if (error.status === 431) {
    if (error.error.success === false) {
    this.presentToast('Something went wrong with the HttpRequest, Please contact Administrator');
    } else {
    console.log(' route this to right place');
    // this.router.navigate(['auth/login']);
    }
    }

    // add all the other error codes here
    return throwError(error);
    }));
    }


    I am not sure what else needs to be added/modified so that the HttpErrorResponse will be intercepted.

    Continue reading...

Compartilhe esta Página