Javascript 角度:从ErrorHandler发出Post请求?
我正在尝试将Angular捕获的任何错误、异常发送到我的服务器。我创建了自己的类GlobalErrorHandler,它扩展了ErrorHandler。请在下面查看Javascript 角度:从ErrorHandler发出Post请求?,javascript,angular,typescript,error-handling,Javascript,Angular,Typescript,Error Handling,我正在尝试将Angular捕获的任何错误、异常发送到我的服务器。我创建了自己的类GlobalErrorHandler,它扩展了ErrorHandler。请在下面查看 import { ErrorHandler, Injectable, Injector } from "@angular/core"; 从“@angular/common/http”导入{HttpHeaders,HttpClient}; 从“./_services/test service.service”导入{TestServi
import { ErrorHandler, Injectable, Injector } from "@angular/core";
从“@angular/common/http”导入{HttpHeaders,HttpClient};
从“./_services/test service.service”导入{TestServiceService}”
每当发生错误时,我都可以控制台.error(error),但我无法向服务器发出post请求
从ErrorHandler发出post请求的代码中缺少了什么?将代码更改为以下内容(将JSON.parse替换为JSON.stringify并成功捕获post错误):
发现错误在服务器端,但如果服务器已正确实现,则上述代码对于试图将客户端错误(Angular2+)传输到服务器的任何人都应该有用。Json parse
error
和sendno good,trusted Json.parse(error),该行从未运行过。这就是你的意思吗?我想这个.http.post(this.url,JSON.stringify(error),httpOptions)就是你的意思meant@JonathanKelsey确切地我错了,但它抓住了错误
@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)
}
}
}
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();}
)
}