I have a call to an HTTP service that return an observable (it's part of a third party library so I cannot change its inner code) and it is throwing an error on the subscribe for a use case that I would like to handle in the happy path.
I have something like this:
My service class:
class MyService {
getEntities(): Observable<any> {
return this.http.get('<the url'>)
.pipe(
catchError(err => {
// Handle the errors and returns a string corresponding to each message.
// Here I show an example with the status code 403
if (err.status === 403) {
return throwError('My error message for 403');
}
// This is what I want to do.
if (err.status === 409) {
// Somehow, make this to trigger the goodResponse in the consumer class.
}
})
);
}
}
My consumer:
class MyComponent {
private myService: MyService;
constructor() {
this.myService = new MyService();
}
callTheAPI() {
this.myService.getEntities()
.subscribe(goodResponse => {
// Handle good response
}, error => {
// Handle error
});
}
}
So, for the current code example, what I want to do is, for the case where the status code is 409, make the subscription to succeed.
Then just return a new Observable (that sends next
item). throwError
sends only the error
notification so you can use of()
:
import { of } from 'rxjs';
...
catchError(err => {
// Handle the errors and returns a string corresponding to each message.
// Here I show an example with the status code 403
if (err.status === 403) {
return throwError('My error message for 403');
}
// This is what I want to do.
if (err.status === 409) {
return of(/* fake response goes here */)
}
})