我正在尝试将任何错误(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发出发布请求的代码中缺少什么?
答案 0 :(得分:0)
将代码更改为以下代码后(将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 +中)传播到服务器的任何人都应该有用。