Home > OS >  How to catch error on subscribe function?
How to catch error on subscribe function?

Time:10-08

I have this functions to upload files in my fileUploadService:

fileUpload(formData: any) {
    return this.http.post(`${this.apiUrl}/upload`, formData, {
      reportProgress: true,
      observe: 'events'
    }).pipe(
      map(event => this.getEventMessage(event))
    );
  }

  private getEventMessage(event: HttpEvent<any>) {
    switch (event.type) {
      case HttpEventType.UploadProgress:
        return this.fileUploadProgress(event);
      case HttpEventType.Response:
        return event.body;
      default:
        return `Upload event: ${event.type}.`;
    }
  }

  private fileUploadProgress(event: any) {
    const percentDone = Math.round(100 * event.loaded / event.total);
    return { progress: percentDone, files: [] };
  }

On one of my components, I call this piece of code:

this.fileUploadService.fileUpload(formData).subscribe(
          result => {
            this.upload = result;
          }
        )

Now my question, if the webserver throws an error so the http post function fails and needs to be catched, how can I catch the error in my component and not in the service?

CodePudding user response:

Observables emit three types of events: next, complete and error. .subscribe() method accepts listeners to all three types either as a list of arguments:

subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null)

Or as a single object argument of type Partial<Observer<T>>:

subscribe(observer?: Partial<Observer<T>>)

Observer<T> has three properties:

export interface Observer<T> {
  complete: () => void;
  error: (err: any) => void;
  next: (value: T) => void;
}

This means you have two options to pass your next and error handlers. Either use:

.fileUpload(formData).subscribe(
  result => console.log('Success!', result),
  error => console.log('Error :(', error),
)

Or:

.fileUpload(formData).subscribe({
  next: result => console.log('Success!', result),
  error: error => console.log('Error :(', error),
})

Second variant is preferable in the community.

  • Related