I'm doing some refactor on my Angular App, and implementing interceptors like a common ErrorHttpInterceptor.
On my tests I noticed My question is, if I remove the "error" paramater from Subscribe on my observables request it trigger an error. If I let it there, the subscribe error trigger, but apparently my app don't break.
I say apparently cause I'm not being able to properly test if the app breaks or not.
This is my "test" method:
testAPI(){
this.myservice.getRequest().subscribe({
next: data => console.log(data),
error: error => console.log(error)
});
}
This is my simplified ErrorInterceptor:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(error => throwError(() => error))
);
}
I want to know if its ok or reliable to leave my Subscribe like this:
testAPI(){
this.myservice.getRequest().subscribe({
next: data => console.log(data)
});
}
And trust solenly on ErrorInterceptor to catch and process errors
CodePudding user response:
If you want your Interceptor to do all your Http Error handling then using Promises and not using subscribe is a cleaner way
Here is a cleaner way of doing it:
Implement your Interceptor like you did but return an EMPTY in your catchError method instead of doing a throw and do a console.error() of the error (you can add the error in a toast as well), because you do not want your app to break everytime an error occurs, you want it to continue.
In your service making the API request:
async saveAddressDetails(user: User): Promise<any> {
return await this.http.post<any>(`${this.authURL}update/address`, user).toPromise();
}
In component where you use the HTTP request:
const result = await this.auth.saveAddressDetails(this.auth.user);
if (result) {
this.toast.success('Address Details saved');
}
Notice that if you have an error result will be null and thus the code in the if will not be computed.