【问题标题】:Handling 500 (Internal Server Error) using HttpClient使用 HttpClient 处理 500(内部服务器错误)
【发布时间】:2019-12-10 19:33:44
【问题描述】:

我使用HttpClient的方式如下:

文件:app.component.ts

    this.appService.getObjectDetail(param)
            .subscribe((response: ObjectDTO) => {
               // Do some stuff
            }, error => {
              var err = `Failed with status = ${error.status}`;
            });

文件:app.services.ts

   public getObjectDetail(path: string): Observable<ObjectDTO> {
        return this.http
            .get(`${this.SERVICE_URL + "/" + path}`).pipe(
                map(response => (<ObjectDTO><any>response)));
    }

当服务器返回时

500(内部服务器错误)

ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:28)
    at subscribeToResult (subscribeToResult.js:15)
    at CatchSubscriber.error (catchError.js:43)
    at XMLHttpRequest.onLoad (http.js:1640)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:24340)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:498)
    at invokeTask (zone.js:1693)

httpclient 调用的回调函数中没有捕获到错误。知道为什么错误没有得到处理吗?

【问题讨论】:

    标签: angular httpclient


    【解决方案1】:

    尝试使用catchError,然后在其中使用throwError。像这样的:

    import { Injectable } from "@angular/core";
    import { HttpClient } from "@angular/common/http";
    
    import { Observable, of, throwError } from "rxjs";
    import { catchError, map } from "rxjs/operators";
    
    @Injectable()
    export class AppService {
      constructor(private http: HttpClient) {}
    
      public getObjectDetail(path: string): Observable<any> {
        return this.http
          .get(`http://jsonplaceholderr.typicode.com/userss/1`)
          .pipe(
            map(response => (<ObjectDTO><any>response)),
            catchError(error => throwError("Something went wrong: ", error))
          );
      }
    }
    

    这样,您就可以在Subscriptionerror 块中处理它。

    这是 StackBlitz 上的 Working Code Example 供您参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      相关资源
      最近更新 更多