gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:25:05 25 4
gpt4 key购买 nike

我按以下方式使用 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 (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 ,然后 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 block 中处理它。

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

关于angular - 使用 HttpClient 处理 500(内部服务器错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59265984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com