Reputation: 2828
I am building a demo angular 7 application where i have generic POST method. While I am able to call this method it seems that none of the errors (401,500 etc) are being captured in the catch block. I can see in the network tab that the post is failed. What is wrong with the below code?
// Generic post method
private async genericPostMethodAsync(url: string, options:any, body: any):Promise<any> {
try {
const response = await this.httpClient.post(url, body,
options).toPromise();
console.log(response);
return response;
} catch (error) {
await this.handleError(error, this);
}
}
private handleError(error: any, any: any): Promise<any> {
return Promise.reject(error.message || error);
}
Upvotes: 3
Views: 1157
Reputation: 2828
It appears that the original code does actually work. All errors are captured in the catch block. The solution was quite simple, update the modules to latest versions (nmp update).
Upvotes: 1
Reputation: 6283
Rxjs 6 has a catch operator that can be found on their site here. I believe you could try the following using what they provide. Little different to the promise you are using but should provide the error catching you are looking for.
( Best could come up with after edit )
Working Solution
Use catchError to get the Http error and then use the of
operator to ensure its returning an observable. Tried and tested in small program working on at the moment and all works just unsure about using promise.
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
public genericPostMethodAsync(text: any): Observable<any> {
return this.httpClient
.post<any>('url', {}).pipe(catchError(val => of(
this.handleError(val)
)));
}
public handleError(val): void {
console.log(val);
}
preferred solution
What i would prefer to do is to look at catching the errors in a subscribe function within the component. So in your component where you call the function try.
this.exampleService.genericPostMethodAsync(url, options, body).subscribe(data => {
console.log(data); // is good.
}, error => {
console.log(error); // is bad.
});
Where your main call within the service using the HTTP and observable s would look like following.
private genericPostMethodAsync(url: string, options:any, body:any):Observable<any> {
return this.httpClient.post(url, body, options).pipe(map(data => data)
);
}
Upvotes: 1
Reputation: 110
try using pipes to catch errors.
for e.g.
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError('getHeroes', []))
);
}
Upvotes: 0