Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

303
Vistas
How to catch error on subscribe function?

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda