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

Handling 500 (Internal Server Error) using 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)));
    }

当服务器returns

500 (Internal Server Error)

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调用的回调函数没有捕获到错误。知道为什么没有处理错误吗?

尝试在其中使用 catchError, and then 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 块中处理它。

Here's a Working Code Example on StackBlitz for your ref.