Javascript catchError中的捕获错误-http.post
正在调用submitUser的组件Javascript catchError中的捕获错误-http.post,javascript,angular,http,rxjs,try-catch,Javascript,Angular,Http,Rxjs,Try Catch,正在调用submitUser的组件 this.someservice.submitUser(postData).subscribe((data) => { this.viewUsers(); }, (err) => { console.log('error in the component', err); }); 这是具有submitUser功能的服务文件 public submitUser(reqBody ) { return t
this.someservice.submitUser(postData).subscribe((data) => {
this.viewUsers();
}, (err) => {
console.log('error in the component', err);
});
这是具有submitUser功能的服务文件
public submitUser(reqBody ) {
return this.httpService.post('roles', reqBody, '/business/create')
.pipe(
catchError(
this.httpService.handleError())
);
}
这是httpService Post和handleError方法
public post<JSON>(url: string, body: any, param?: string, options?: IRequestOptions): Observable<JSON> {
return this.intercept(this.http.post<JSON>(this.getURLFromMethodName(url, param), body, this.requestOptions(options)));
}
public post(url:string,body:any,param?:string,options?:IRequestOptions):可观察{
返回this.intercept(this.http.post(this.getURLFromMethodName(url,param),body,this.requestOptions(options));
}
handleError(操作='operation',结果?:T){
返回(错误:任意):可观察=>{
//TODO:将错误发送到远程日志记录基础结构
错误('error from httpclient',error);//改为登录到控制台
投掷器(新错误(错误));
};
}
handleError A显示控制台错误,我试图在service.ts中的submitUser函数中返回/捕获此错误
我该怎么做?感谢您的handleError()
方法返回一个可观察到的错误
,并将错误记录到控制台
当出现错误时,catchError
操作符将该错误传递给handleError()
,后者反过来返回一个可观察到的错误
案例1:返回错误
如果需要将此错误传递给订阅服务器,则无需执行任何操作。catchError
操作员已经为您处理好了
使用相同的代码,假设某个组件正在使用您的服务,那么您只需编写
someService.submitUser().subscribe((res) => {
\\ handle success
}, (err) => {
console.error(err); // Will print the error
});
每当错误发生时,catchError将把可观察到的错误返回给它的订阅者,它将进入观测者的error函数,如上面的代码片段所示
案例2:处理错误
catchError
运算符接受将error
作为参数的函数。如果您在其中返回另一个observable,而不是抛出一个错误,那么订阅者将无法知道错误已经发生,observable的success函数将执行
// Inside the service
public submitUser(reqBody ) {
return this.httpService.post('roles', reqBody, '/business/create')
.pipe(
catchError((err) => of([1,2,3]));
}
// Inside the component consuming the service
someService.submitUser().subscribe((res) => {
console.log(res) // Will print [1,2,3]
}, (err) => {
\\ handle error
});
this.manageAccessService.submitUser(postData).subscribe((数据)=>{this.viewUsers();},(err)=>{console.log('error in the component',err);})
我在我的组件中这样做了,但是如何从handleError方法捕获错误您的handleError
函数返回一个抛出可观察错误的函数,catchError
获取此函数并向订阅方抛出相同的错误。这意味着,组件subscribe方法中的err
变量应该有handleError
函数抛出的错误。组件中的err返回一个可观察的可观察的{u isScalar:false,_subscribe:ƒ}如何在handleError函数中解析它,而不是throwError(新错误(error))代码>,使用返回投掷器(新错误(Error))代码>组件中的错误打印错误:[object]是否有我们需要通过catchError传递的内容?
// Inside the service
public submitUser(reqBody ) {
return this.httpService.post('roles', reqBody, '/business/create')
.pipe(
catchError((err) => of([1,2,3]));
}
// Inside the component consuming the service
someService.submitUser().subscribe((res) => {
console.log(res) // Will print [1,2,3]
}, (err) => {
\\ handle error
});