使用HttpClient处理500(内部服务器错误)

时间:2019-12-10 11:15:56

标签: angular httpclient

我通过以下方式使用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调用的回调函数未捕获该错误。知道为什么不处理该错误?

1 个答案:

答案 0 :(得分:5)

尝试使用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))
      );
  }
}

这样,您将可以在error的{​​{1}}块中对其进行处理。

  

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