簡體   English   中英

Angular 8 攔截和修改Http錯誤響應

[英]Angular 8 Intercept and modify Http Error Response

我需要攔截和修改一個 HttpResponse,它是 HttpErrorResponse 的實例,即狀態:500,狀態為 200 並填寫其正文,以便我可以在我的 http.post 的 Observable 訂閱中處理它作為成功的 http 調用。

我設法使用以下攔截器修改了 HttpErrorResponse:

export class CustomErrorHttpInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      catchError((httpErrorResponse: HttpErrorResponse) => {

        // Customize as you wish:
        const newHttpErrorResponse = new HttpErrorResponse( {
          error: httpErrorResponse.error,
          headers: httpErrorResponse.headers,
          status: httpErrorResponse.status,
          statusText: httpErrorResponse.statusText,
          url: httpErrorResponse.url
        });

        return Observable.throw(newHttpErrorResponse);
      })
    );
  }
}

您可以使用catchError map運算符和 catchError 來處理錯誤。 這里的代碼:

const withoutError = this.http
      .get("https://httpstat.us/500")
      .pipe(
          catchError((error) => {
          // here you can modify your error
          return of(error)
       })
      )
      .subscribe(res => {
        console.log("Run, because error has modified", res.status);
      }, (error) => {
        console.log('Never run ...')
      });

https://httpstat.us/500總是以 500 狀態代碼響應。

在這里你可以看到它是如何工作的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM