Search code examples
angularangular2-servicesangular2-componentsangular2-observables

My subscription is not handling errors


I have a subscription to a service where I request image URLs from an external API and store it in a shared service.

The Logic:
1. Empty the current images array
2. Request images from API, and push it to the (newly cleared) array (response =>)
3. If the URL returns an error, fill up the array with default (placeholder) images (error =>)

For some reason, the error isn't being handled despite there being one. I have posted my component and error messages for context.

Component.ts

  getImages(vehicleID: number, color: string): void {
    this._carConfigService.car.colors.exterior.urls = [];
    this._FAPIService.getImagesForColors(vehicleID, color)
      .subscribe(
        response => {
        response.products[0].productFormats.forEach(pF => {
        this._carConfigService.car.colors.exterior.urls.push(pF.assets[0].url);
        });
      },
        error => {
          this.errorMessage = <any>error;
          if (this._carConfigService.car.colors.exterior.urls.length === 0) {
            this._carConfigService.car.colors.exterior.urls = this._carConfigService.defaultImages;
          }
      });
  }

I receive the following errors:

Failed to load resource: the server responded with a status of 422 ()
EXCEPTION: Response with status: 0  for URL: null
Uncaught Response

Solution

  • You need to handle them using a regular approach of having exception handling

    export class TaskService {
        private _url = "api/products/datanew.json";
        constructor(private _http: Http) {
        }
        getTasks(): Observable<any[]> {
            return this._http.get(this._url)
                .map((response: Response) => <any[]>response.json())
                .do(data => console.log("data we got is " + JSON.stringify(data)))
                .catch(this.handleError);
    
        }
        private handleError(error: Response) {
                console.log(error);
                return Observable.throw(error.json().error || 'Internal Server error');
        }
    }
    

    Also, I have a question.

    1. you are getting data but you are not assigning to any object? No return type