gpt4 book ai didi

javascript - Angular : Make Post Request From ErrorHandler?

转载 作者:行者123 更新时间:2023-12-03 08:46:52 24 4
gpt4 key购买 nike

我正在尝试将任何错误,Angular捕获的异常发送到我的服务器。我制作了自己的名为GlobalErrorHandler的类,该类扩展了ErrorHandler。请在下面检查

import { ErrorHandler, Injectable, Injector } from "@angular/core";

从“@ angular/common/http”导入{HttpHeaders,HttpClient};
从“../_services/test-service.service”导入{TestServiceService};
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(
private injector: Injector,
private http: HttpClient,
private service: TestServiceService,
) {}

url = 'http://127.0.0.1:4000/post';

handleError(error) {
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};

try {

let msg = JSON.parse(error)
console.log('>>>>>>>>> message is ', msg)
this.http.post(this.url, msg, httpOptions);

}
catch (e) {
console.log('>>>>>>>>> err in catch is ', e)
}
}
}

每当发生错误时,我都可以console.error(error),但是我无法向服务器发出发布请求。

我从ErrorHandler发出发布请求的代码中缺少什么?

最佳答案

将代码更改为以下代码后(将JSON.parse替换为JSON.stringify并成功捕获发布错误):

handleError(error) { 
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};

let subscription = this.http.post(this.url, JSON.stringify(error), httpOptions).subscribe(
(data => {console.log('>>>>>>> data is ', data));subscription.unsubscribe();},
error => {console.log('>>>>>>>> err', error);subscription.unsubscribe();}
)

}

错误被发现在服务器端,但是只要服务器已正确实现,上面的代码对于尝试将客户端错误(在Angular2 +中)传播到服务器的任何人都应该有用。

关于javascript - Angular : Make Post Request From ErrorHandler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51774328/

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