How to deal with http status codes other than 200 in Angular 2

前端 未结 2 1342
走了就别回头了
走了就别回头了 2020-11-30 23:17

Right now the way I do http requests (borrowed from this answer) is this:

POST(url, data) {
        var headers = new Headers(), authtoken = localStorage.get         


        
相关标签:
2条回答
  • 2020-11-30 23:59

    Include required imports and you can make ur decision in handleError method Error status will give the error code

    import { HttpClient, HttpErrorResponse } from '@angular/common/http';
    import {Observable, throwError} from "rxjs/index";
    import { catchError, retry } from 'rxjs/operators';
    import {ApiResponse} from "../model/api.response";
    import { TaxType } from '../model/taxtype.model'; 
    
    private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
      };
    
      getTaxTypes() : Observable<ApiResponse> {
    return this.http.get<ApiResponse>(this.baseUrl).pipe(
      catchError(this.handleError)
    );
      }
    
    0 讨论(0)
  • 2020-12-01 00:17

    Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs for the same like this way

    import {Observable} from 'rxjs/Rx';
    
    return this.http.request(new Request(this.requestoptions))
                .map((res: Response) => {
                    if (res) {
                        if (res.status === 201) {
                            return [{ status: res.status, json: res }]
                        }
                        else if (res.status === 200) {
                            return [{ status: res.status, json: res }]
                        }
                    }
                }).catch((error: any) => {
                    if (error.status === 500) {
                        return Observable.throw(new Error(error.status));
                    }
                    else if (error.status === 400) {
                        return Observable.throw(new Error(error.status));
                    }
                    else if (error.status === 409) {
                        return Observable.throw(new Error(error.status));
                    }
                    else if (error.status === 406) {
                        return Observable.throw(new Error(error.status));
                    }
                });
        }
    

    also you can handel error (with err block) that is throw by catch block while .map function,

    like this -

    ...
    .subscribe(res=>{....}
               err => {//handel here});
    

    Update

    as required for any status without checking particluar one you can try this: -

    return this.http.request(new Request(this.requestoptions))
                .map((res: Response) => {
                    if (res) {
                        if (res.status === 201) {
                            return [{ status: res.status, json: res }]
                        }
                        else if (res.status === 200) {
                            return [{ status: res.status, json: res }]
                        }
                    }
                }).catch((error: any) => {
                    if (error.status < 400 ||  error.status ===500) {
                        return Observable.throw(new Error(error.status));
                    }
                })
                .subscribe(res => {...},
                           err => {console.log(err)} );
    
    0 讨论(0)
提交回复
热议问题