【问题标题】:How to catch error on subscribe function?如何在订阅功能上捕获错误?
【发布时间】:2021-11-27 14:09:14
【问题描述】:

我有这个功能可以在我的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: [] };
  }

在我的一个组件上,我将这段代码称为:

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

现在我的问题是,如果网络服务器抛出错误导致 http post 功能失败并需要被捕获,我如何才能在我的组件中而不是在服务中捕获错误?

【问题讨论】:

  • 试试.fileUpload(formData).subscribe( result =&gt; { ... } , error =&gt; { ... } ) ?

标签: javascript node.js angular typescript


【解决方案1】:

Observables 发出三种类型的事件:nextcompleteerror.subscribe() 方法接受所有三种类型的侦听器作为参数列表:

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

或者作为Partial&lt;Observer&lt;T&gt;&gt;类型的单个对象参数:

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

Observer&lt;T&gt; 具有三个属性:

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

这意味着您有两个选项来传递您的 nexterror 处理程序。要么使用:

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

或者:

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

第二个变体在社区中更受欢迎。

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 2012-08-13
    • 2020-09-21
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2019-07-26
    • 2012-05-26
    相关资源
    最近更新 更多