angular - 如何在Angular中使用catchErroŕRxJS运算符进行错误处理?

标签 angular typescript error-handling rxjs observable

我是Angular/Typescript的新手,正在使用catchError RxJs。我还使用.subscribe和pipe运算符。我想尽可能地将observable与RxJS运算符结合使用。提交表单后,前端会调用API,并创建一个新产品,并希望使用HttpErrorResponse对400和500的错误代码进行适当的错误处理。
我写了下面的代码,但不确定出现以下错误时是否正确处理了错误(请参阅底部)。

app.component.ts

onSubmit(): void {
    if (this.form.valid) {
        console.log('Creating product:', this.form.value);
        this.http.post('/api/create', {
            productName: this.form.value.productName,
        }).pipe(catchError(err => {
            if(err instanceof HttpErrorResponse && err.status == 500 || err.status == 502 || err.status == 503) {
                this.err = "Server Side Error";
                return throwError(err);;
            }
            else if(err instanceof HttpErrorResponse && err.status == 400){
                this.err = "Bad Request";
                return throwError(err);;
            } else if(err instanceof HttpErrorResponse && err.status == 422){
                this.err = "Unprocessable Entity - Invalid Parameters";
                return throwError(err);;
            }
        })
          .subscribe(
            resp => this.onSubmitSuccess(resp), err => this.onSubmitFailure(err)
        );
    }
    this.formSubmitAttempt = true;
}

private onSubmitSuccess(resp) {
    console.log('HTTP response', resp);
    this.productID = resp.projectID;
    this.submitSuccess = true;
    this.submitFailed = false;
}

private onSubmitFailure(err) {
    console.log('HTTP Error', err);
    this.submitFailed = true;
    this.submitSuccess = false;
}

错误:

app.component.ts-错误TS2339:类型“AppComponent”上不存在属性“err”。

app.component.ts:124:16-错误TS2339:类型“OperatorFunction”上不存在属性“订阅”。})。subscribe(

最佳答案

为了解决您的问题,我修改了代码,如下所示。


      onSubmit(): void {
    if (this.form.valid) {
        console.log('Creating product:', this.form.value);
        this.http.post('/api/create', {
            productName: this.form.value.productName,
        }).pipe(catchError(errorResponse=> {

        const err = <HttpErrorResponse>errorResponse;

        if (err && err.status === 422) {
           this.err = "Unprocessable Entity - Invalid Parameters";
                return throwError(err);            
        } else if (err && err.status === 400) {
                this.err = "Bad Request";
                return throwError(err);;      
        } else if (err && err.status === 404) {
          this.err = "Not found";
                return throwError(err);;    
        } else if (
          err &&
          (err.status < 200 || err.status <= 300 || err.status >= 500)
        ) {
            this.err = "Server Side Error";
                return throwError(err);;
        }
        })
          .subscribe(
            resp => this.onSubmitSuccess(resp), err => this.onSubmitFailure(err)
        );
    }
    this.formSubmitAttempt = true;
}

我建议创建一个可处理任何异常的通用异常服务。您应该将传出的API调用分离到单独的服务,然后在组件中使用它。易于阅读和维护代码。请尝试以下代码逻辑。
import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable()
export class ExceptionService {
  constructor(private toastService: ToastService) {}

  catchBadResponse: (errorResponse: any) => Observable<any> = (
    errorResponse: any
  ) => {
    let res = <HttpErrorResponse>errorResponse;
    let err = res;
    let emsg = err
      ? err.error
        ? err.error
        : JSON.stringify(err)
      : res.statusText || 'unknown error';
console.log(`Error - Bad Response - ${emsg}`);
    return of(false);
  };
}

在您的服务中,您可以创建像这样的发布方法
saveEntity(entityToSave: EntityToSave) {
    return <Observable<EntityToSave>>(
      this.http.post(`${postURL}`, entityToSave).pipe(
        map((res: any) => <EntityToSave>res),
        catchError(this.exceptionService.catchBadResponse),
        finalize(() => console.log('done'))
      )
    );
  }

从您的组件中,调用处理异常的服务
   this.yourService.saveEntity(entityToSave).subscribe(s => {
       //do your work... this get called when the post call was successfull
      });

希望它能解决您的问题。

关于angular - 如何在Angular中使用catchErroŕRxJS运算符进行错误处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62440588/

相关文章:

angular - 如何在 Angular 2 的方法中创建 @ViewChild 临时变量?

javascript - 在componentDidCatch之后重定向用户的方法

error-handling - super.init调用未初始化属性 'self.animator'

java - 为什么当我停止从按钮 Action 监听器播放音频时出现此错误(音频从 Thread 运行)整个代码都在里面

javascript - 将外部 js 文件包含到 angular 5.0.0 项目中

angular - MatDialog Angular 开放组件?

angular - 拖放图片上传,angular 4

node.js - 错误 TS2430 : Interface 'WebGLRenderingContext' incorrectly extends interface 'WebGLRenderingContextBase'

Angular 4 : get error message in subscribe

javascript - Angular - 多次使用的组件是否完全是自己创建的?