कोणीय HttpClient में त्रुटियों को पकड़ना


114

मेरे पास एक डेटा सेवा है जो इस तरह दिखती है:

@Injectable()
export class DataService {
    baseUrl = 'http://localhost'
        constructor(
        private httpClient: HttpClient) {
    }
    get(url, params): Promise<Object> {

        return this.sendRequest(this.baseUrl + url, 'get', null, params)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    post(url, body): Promise<Object> {
        return this.sendRequest(this.baseUrl + url, 'post', body)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    patch(url, body): Promise<Object> {
        return this.sendRequest(this.baseUrl + url, 'patch', body)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    sendRequest(url, type, body, params = null): Observable<any> {
        return this.httpClient[type](url, { params: params }, body)
    }
}

अगर मुझे HTTP एरर (यानी 404) मिलता है, तो मुझे एक नॉटी कंसोल संदेश मिलता है: ERROR एरर: अनकवर्ड (वादे में): core.es5.js से [ऑब्जेक्ट ऑब्जेक्ट] मैं अपने मामले में इसे कैसे हैंडल करूं?

जवाबों:


231

आपकी जरूरतों के आधार पर आपके पास कुछ विकल्प हैं। यदि आप प्रति-अनुरोध के आधार पर त्रुटियों को संभालना चाहते हैं, तो catchअपने अनुरोध में एक जोड़ें । यदि आप एक वैश्विक समाधान जोड़ना चाहते हैं, तो उपयोग करें HttpInterceptor

नीचे दिए गए समाधानों के लिए यहां कार्यरत डेमो प्लंकर खोलें ।

tl; डॉ

सबसे सरल मामले में, आपको बस एक .catch()या एक जोड़ने की आवश्यकता होगी .subscribe(), जैसे:

import 'rxjs/add/operator/catch'; // don't forget this, or you'll get a runtime error
this.httpClient
      .get("data-url")
      .catch((err: HttpErrorResponse) => {
        // simple logging, but you can do a lot more, see below
        console.error('An error occurred:', err.error);
      });

// or
this.httpClient
      .get("data-url")
      .subscribe(
        data => console.log('success', data),
        error => console.log('oops', error)
      );

लेकिन इसके बारे में अधिक विवरण हैं, नीचे देखें।


विधि (स्थानीय) समाधान: लॉग त्रुटि और वापसी वापसी प्रतिक्रिया

यदि आपको केवल एक ही स्थान पर त्रुटियों को संभालने की आवश्यकता है, तो आप catchपूरी तरह से विफल होने के बजाय एक डिफ़ॉल्ट मान (या खाली प्रतिक्रिया) का उपयोग और वापस कर सकते हैं । आपको .mapबस कास्ट करने की आवश्यकता नहीं है , आप एक सामान्य फ़ंक्शन का उपयोग कर सकते हैं। स्रोत: Angular.io - त्रुटि विवरण प्राप्त करना

तो, एक सामान्य .get()विधि, इस तरह होगी:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry'; // don't forget the imports

@Injectable()
export class DataService {
    baseUrl = 'http://localhost';
    constructor(private httpClient: HttpClient) { }

    // notice the <T>, making the method generic
    get<T>(url, params): Observable<T> {
      return this.httpClient
          .get<T>(this.baseUrl + url, {params})
          .retry(3) // optionally add the retry
          .catch((err: HttpErrorResponse) => {

            if (err.error instanceof Error) {
              // A client-side or network error occurred. Handle it accordingly.
              console.error('An error occurred:', err.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 ${err.status}, body was: ${err.error}`);
            }

            // ...optionally return a default fallback value so app can continue (pick one)
            // which could be a default value
            // return Observable.of<any>({my: "default value..."});
            // or simply an empty observable
            return Observable.empty<T>();
          });
     }
}

त्रुटि को संभालने से आपको एप्लिकेशन तब भी जारी रखने की अनुमति मिलेगी जब URL पर सेवा खराब स्थिति में हो।

यह प्रति-अनुरोध समाधान ज्यादातर अच्छा है जब आप प्रत्येक विधि के लिए एक विशिष्ट डिफ़ॉल्ट प्रतिक्रिया लौटना चाहते हैं। लेकिन अगर आप केवल त्रुटि प्रदर्शित करने के बारे में परवाह करते हैं (या एक वैश्विक डिफ़ॉल्ट प्रतिक्रिया है), तो बेहतर उपाय यह है कि इंटरसेप्टर का उपयोग करें, जैसा कि नीचे वर्णित है।

यहां काम कर रहे डेमो प्लंकर चलाएं ।


उन्नत उपयोग: सभी अनुरोधों या प्रतिक्रियाओं को इंटरसेप्ट करना

एक बार फिर, Angular.io गाइड दिखाता है:

@angular/common/httpइंटरसेप्शन की एक प्रमुख विशेषता इंटरसेप्टर घोषित करने की क्षमता है, जो आपके आवेदन और बैकएंड के बीच में बैठती है। जब आपका आवेदन एक अनुरोध करता है, तो इंटरसेप्टर्स इसे सर्वर पर भेजने से पहले बदल देते हैं, और इंटरसेप्टर आपके आवेदन को देखने से पहले प्रतिक्रिया को अपने तरीके से बदल सकते हैं। यह प्रमाणीकरण से लेकर लॉगिंग तक सब कुछ के लिए उपयोगी है।

जो, निश्चित रूप से, त्रुटियों को बहुत ही सरल तरीके से संभालने के लिए इस्तेमाल किया जा सकता है ( डेमो प्लंकर यहां ):

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse,
         HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry'; // don't forget the imports

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
      .catch((err: HttpErrorResponse) => {

        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', err.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 ${err.status}, body was: ${err.error}`);
        }

        // ...optionally return a default fallback value so app can continue (pick one)
        // which could be a default value (which has to be a HttpResponse here)
        // return Observable.of(new HttpResponse({body: [{name: "Default value..."}]}));
        // or simply an empty observable
        return Observable.empty<HttpEvent<any>>();
      });
  }
}

अपने इंटरसेप्टर प्रदान करना: बस HttpErrorInterceptorउपरोक्त घोषित करने से आपका ऐप इसका उपयोग नहीं कर सकता है। आपको इसे अपने ऐप मॉड्यूल में एक इंटरसेप्टर के रूप में प्रदान करके तार करना होगा , जो निम्नानुसार है:

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpErrorInterceptor } from './path/http-error.interceptor';

@NgModule({
  ...
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: HttpErrorInterceptor,
    multi: true,
  }],
  ...
})
export class AppModule {}

नोट: यदि आपके पास दोनों एक त्रुटि इंटरसेप्टर और कुछ स्थानीय त्रुटि हैंडलिंग, स्वाभाविक रूप से, यह संभव है कि कोई स्थानीय त्रुटि हैंडलिंग कभी, ट्रिगर किया जाएगा के बाद से त्रुटि हमेशा इंटरसेप्टर द्वारा नियंत्रित किया जाएगा है इससे पहले कि यह स्थानीय त्रुटि हैंडलिंग तक पहुँचता है।

चलाएं यहां काम कर रहे डेमो प्लंकर


2
ठीक है, अगर वह पूरी तरह से फैंसी होना चाहता है तो वह अपनी सेवा पूरी तरह से छोड़ देगा return this.httpClient.get<type>(...):। और फिर catch...उस सेवा से कहीं बाहर है जहां वह वास्तव में इसका उपभोग करता है क्योंकि यही वह जगह है जहां वह वेधशालाओं के प्रवाह का निर्माण करेगा और इसे सबसे अच्छे से संभाल सकता है।
dee zg

1
मैं सहमत हूं, शायद एक इष्टतम समाधान त्रुटि को संभालने के लिए Promise<Object>ग्राहक ( DataServiceविधियों के कॉलर ) के लिए होगा। उदाहरण: this.dataService.post('url', {...}).then(...).catch((e) => console.log('handle error here instead', e));। आपके और आपकी सेवा के उपयोगकर्ताओं के लिए जो कुछ भी स्पष्ट है उसे चुनें।
अक्टूबर को acdcjunior

1
यह संकलित नहीं करता है: return Observable.of({my: "default value..."}); यह एक त्रुटि देता है "..." ... 'HttpEvent <any>' टाइप करने के लिए असाइन नहीं किया जाता है।
याकॉव फेन

1
@YakovFain यदि आप इंटरसेप्टर में एक डिफ़ॉल्ट मान चाहते हैं, तो यह एक होना चाहिए HttpEvent, जैसे कि ए HttpResponse। उदाहरण के लिए, आप उपयोग कर सकते हैं return Observable.of(new HttpResponse({body: [{name: "Default value..."}]}));:। मैंने इस बिंदु को स्पष्ट करने के लिए उत्तर को अपडेट कर दिया है। इसके अलावा, मैंने सब कुछ काम करने के लिए एक वर्किंग डेमो प्लंकर बनाया: plnkr.co/edit/ulFGp4VMzrbaDJeGqc6q?p=preview
acdcjunior

1
@acdcjunior, आप एक उपहार हैं जो देता रहता है :)
LastTribunal

67

मुझे नवीनतम RxJs सुविधाओं (v.6) के साथ HttpInterceptor का उपयोग करने के बारे में acdcjunior के जवाब को अपडेट करने दें

import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpErrorResponse,
  HttpHandler,
  HttpEvent,
  HttpResponse
} from '@angular/common/http';

import { Observable, EMPTY, throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.error instanceof Error) {
          // 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}`);
        }

        // If you want to return a new response:
        //return of(new HttpResponse({body: [{name: "Default value..."}]}));

        // If you want to return the error on the upper level:
        //return throwError(error);

        // or just return nothing:
        return EMPTY;
      })
    );
  }
}

11
इसके लिए और अधिक उत्थान की आवश्यकता है। acdcjunior का उत्तर आज के रूप में अनुपयोगी है
पॉल क्रूगर

48

HTTPClientएपीआई के आगमन के साथ , न केवल Httpएपीआई को बदल दिया गया था , बल्कि एक नया जोड़ा गया था, HttpInterceptorएपीआई।

AFAIK का एक लक्ष्य अपने सभी HTTP निवर्तमान अनुरोधों और आने वाली प्रतिक्रियाओं के लिए डिफ़ॉल्ट व्यवहार जोड़ना है।

इसलिए यह मानते हुए कि आप डिफ़ॉल्ट त्रुटि हैंडलिंग व्यवहार को जोड़ना चाहते हैं , जोड़ना.catch() चाहते हैं, अपने सभी संभव http.get / post / etc तरीकों को जोड़ना हास्यास्पद बनाए रखना मुश्किल है।

यह निम्नलिखित तरीके से किया जा सकता है उदाहरण के लिए एक का उपयोग करके HttpInterceptor:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { _throw } from 'rxjs/observable/throw';
import 'rxjs/add/operator/catch';

/**
 * Intercepts the HTTP responses, and in case that an error/exception is thrown, handles it
 * and extract the relevant information of it.
 */
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    /**
     * Intercepts an outgoing HTTP request, executes it and handles any error that could be triggered in execution.
     * @see HttpInterceptor
     * @param req the outgoing HTTP request
     * @param next a HTTP request handler
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req)
            .catch(errorResponse => {
                let errMsg: string;
                if (errorResponse instanceof HttpErrorResponse) {
                    const err = errorResponse.message || JSON.stringify(errorResponse.error);
                    errMsg = `${errorResponse.status} - ${errorResponse.statusText || ''} Details: ${err}`;
                } else {
                    errMsg = errorResponse.message ? errorResponse.message : errorResponse.toString();
                }
                return _throw(errMsg);
            });
    }
}

/**
 * Provider POJO for the interceptor
 */
export const ErrorInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true,
};

// app.module.ts

import { ErrorInterceptorProvider } from 'somewhere/in/your/src/folder';

@NgModule({
   ...
   providers: [
    ...
    ErrorInterceptorProvider,
    ....
   ],
   ...
})
export class AppModule {}

ओपी के लिए कुछ अतिरिक्त जानकारी: http.get / post / etc को एक मजबूत प्रकार के बिना कॉल करना एपीआई का इष्टतम उपयोग नहीं है। आपकी सेवा इस तरह दिखनी चाहिए:

// These interfaces could be somewhere else in your src folder, not necessarily in your service file
export interface FooPost {
 // Define the form of the object in JSON format that your 
 // expect from the backend on post
}

export interface FooPatch {
 // Define the form of the object in JSON format that your 
 // expect from the backend on patch
}

export interface FooGet {
 // Define the form of the object in JSON format that your 
 // expect from the backend on get
}

@Injectable()
export class DataService {
    baseUrl = 'http://localhost'
    constructor(
        private http: HttpClient) {
    }

    get(url, params): Observable<FooGet> {

        return this.http.get<FooGet>(this.baseUrl + url, params);
    }

    post(url, body): Observable<FooPost> {
        return this.http.post<FooPost>(this.baseUrl + url, body);
    }

    patch(url, body): Observable<FooPatch> {
        return this.http.patch<FooPatch>(this.baseUrl + url, body);
    }
}

के Promisesबजाय अपनी सेवा विधियों से लौटना Observablesएक और बुरा निर्णय है।

और सलाह का एक अतिरिक्त टुकड़ा: यदि आप TYPE स्क्रिप्ट का उपयोग कर रहे हैं , तो इसके प्रकार का उपयोग करना शुरू करें। आप भाषा के सबसे बड़े लाभों में से एक को खो देते हैं: उस मूल्य के प्रकार को जानने के लिए जिसे आप के साथ काम कर रहे हैं।

यदि आप मेरी राय में, कोणीय सेवा का अच्छा उदाहरण चाहते हैं , तो निम्नलिखित सार पर एक नज़र डालें ।


टिप्पणियाँ विस्तारित चर्चा के लिए नहीं हैं; इस वार्तालाप को बातचीत में स्थानांतरित कर दिया गया है ।
deceze

मुझे लगता है यह होना चाहिए this.http.get()आदि और में नहीं this.get()आदि DataService?
डिस्प्लेनेम

चयनित उत्तर अब अधिक पूर्ण प्रतीत होता है।
क्रिस हैन्स

9

बहुत सीधा (पिछले एपीआई के साथ यह कैसे किया गया था की तुलना में)।

स्रोत से (कॉपी और पेस्ट किया गया) कोणीय आधिकारिक गाइड

 http
  .get<ItemsResponse>('/api/items')
  .subscribe(
    // Successful responses call the first callback.
    data => {...},
    // Errors will call this callback instead:
    err => {
      console.log('Something went wrong!');
    }
  );

9

कोणीय 6+ के लिए .catch सीधे ऑब्जर्वेबल के साथ काम नहीं करता है। आपको उपयोग करना होगा

.pipe(catchError(this.errorHandler))

नीचे कोड:

import { IEmployee } from './interfaces/employee';
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  private url = '/assets/data/employee.json';

  constructor(private http: HttpClient) { }

  getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url)
                    .pipe(catchError(this.errorHandler));  // catch error
  }

  /** Error Handling method */

  errorHandler(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.');
  }
}

अधिक जानकारी के लिए, Http के लिए कोणीय गाइड देखें


1
यह एकमात्र उत्तर है जिसने मेरे लिए काम किया। अन्य लोग एक त्रुटि देते हैं: "टाइप 'ऑब्जर्वेबल <अज्ञात>' टाइप करने योग्य नहीं है" ऑब्जर्वेबल <HttpEvent <किसी भी >> "।
राजा आर्थर

5

कोणीय 8 HttpClient त्रुटि हैंडलिंग सेवा उदाहरण

यहां छवि विवरण दर्ज करें

api.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
    import { Student } from '../model/student';
    import { Observable, throwError } from 'rxjs';
    import { retry, catchError } from 'rxjs/operators';

    @Injectable({
      providedIn: 'root'
    })
    export class ApiService {

      // API path
      base_path = 'http://localhost:3000/students';

      constructor(private http: HttpClient) { }

      // Http Options
      httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      }

      // Handle API errors
      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.');
      };


      // Create a new item
      createItem(item): Observable<Student> {
        return this.http
          .post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
          .pipe(
            retry(2),
            catchError(this.handleError)
          )
      }

     ........
     ........

    }

2

आप शायद इस तरह से कुछ करना चाहते हैं:

this.sendRequest(...)
.map(...)
.catch((err) => {
//handle your error here
})

यह अत्यधिक निर्भर करता है कि आप अपनी सेवा का उपयोग कैसे करते हैं लेकिन यह मूल मामला है।


1

@Acdcjunior जवाब के बाद, यह है कि मैंने इसे कैसे लागू किया

सर्विस:

  get(url, params): Promise<Object> {

            return this.sendRequest(this.baseUrl + url, 'get', null, params)
                .map((res) => {
                    return res as Object
                }).catch((e) => {
                    return Observable.of(e);
                })
                .toPromise();
        }

फोन करने वाले:

this.dataService.get(baseUrl, params)
            .then((object) => {
                if(object['name'] === 'HttpErrorResponse') {
                            this.error = true;
                           //or any handle
                } else {
                    this.myObj = object as MyClass 
                }
           });

1

import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

const PASSENGER_API = 'api/passengers';

getPassengers(): Observable<Passenger[]> {
  return this.http
    .get<Passenger[]>(PASSENGER_API)
    .pipe(catchError((error: HttpErrorResponse) => throwError(error)));
}

0

यदि आप स्वयं को यहां दिए गए किसी भी समाधान के साथ त्रुटियों को पकड़ने में असमर्थ पाते हैं, तो यह हो सकता है कि सर्वर कोरस अनुरोधों को संभाल नहीं रहा है।

उस घटना में, जावास्क्रिप्ट, बहुत कम कोणीय, त्रुटि जानकारी तक पहुंच सकता है।

अपने कंसोल में चेतावनियाँ देखें जिनमें शामिल हैं CORBया Cross-Origin Read Blocking

साथ ही, त्रुटियों को संभालने के लिए सिंटैक्स बदल गया है (जैसा कि हर दूसरे उत्तर में वर्णित है)। अब आप पाइप-सक्षम ऑपरेटरों का उपयोग करते हैं, जैसे:

this.service.requestsMyInfo(payload).pipe(
    catcheError(err => {
        // handle the error here.
    })
);

0

इंटरसेप्टर का उपयोग करके आप त्रुटि पकड़ सकते हैं। नीचे कोड है:

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //Get Auth Token from Service which we want to pass thr service call
    const authToken: any = `Bearer ${sessionStorage.getItem('jwtToken')}`
    // Clone the service request and alter original headers with auth token.
    const authReq = req.clone({
      headers: req.headers.set('Content-Type', 'application/json').set('Authorization', authToken)
    });

    const authReq = req.clone({ setHeaders: { 'Authorization': authToken, 'Content-Type': 'application/json'} });

    // Send cloned request with header to the next handler.
    return next.handle(authReq).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        console.log("Service Response thr Interceptor");
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        console.log("err.status", err);
        if (err.status === 401 || err.status === 403) {
          location.href = '/login';
          console.log("Unauthorized Request - In case of Auth Token Expired");
        }
      }
    });
  }
}

आप इस ब्लॉग को पसंद कर सकते हैं .. इसके लिए सरल उदाहरण दें।

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.