RXJS throw error in a fromPromise does not hit 'catchError' piped method - rxjs

Can someone explain why this promise (runQuery) , which fails into the 'catch' and throws an ErrorObservable, does not get caught in the 'catchError' method, but goes into 'map' method.
( I tried both _throw/ErrorObservable approach, same result )
import { _throw } from 'rxjs/observable/throw';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
const runQuery = ( Promise that rejects )
const source$ = fromPromise(
runQuery({ d: 'g' })
.catch(err => {
return new ErrorObservable(err);
//return _throw(err); -- same as above
})
)
.pipe(
map((response: any) => {
//ENTERS HERE as response.error
}),
catchError(e => {
//DOES NOT ENTER
})
);

You are handling your own error in the promise and let it return an ErrorObservable. By doing so you made the promise succeed (although with an error like return value). fromPromise will convert this in an emission instead of error.
Remove the catch case in the fromPromise and it should hit the Observable.catchError

I made a live example to prove my point.
There is no need to handle the promise (when it is still a promise), so this far from recommendable.
.then(data => {
return data;
})
.catch(err => {
return new ErrorObservable(err);
//return _throw(err); -- same as above
}))
Let observables take control of rejections
const source$ = fromPromise(runQuery())
.pipe(
map((response: any) => {
//Make here some transformations
return response;
}),
catchError(e => {
return _throw(e);
}
));

If you want to change the error object or do a console.log() inside the catch in the promise before the observable receives the error you can throw the error:
.then(data => {
return data;
})
.catch(err => {
console.error("Error", err );
err.code = 110; // you may want to change something before passing to observable
throw err;
}))
If you use return error the error or catch pipe of the observable won't work, but using throw it works.

Related

Angular 9/rxjs: How to handle an error thrown inside switchMap?

I'm using Angular (9) powered Bootstrap (6.1.0) TypeAhead and defining its search function like so:
search = (text$: Observable<string>) => {
return text$.pipe(
debounceTime(200),
distinctUntilChanged(),
// switchMap allows returning an observable rather than maps array
switchMap((searchText) => {
if (!searchText || searchText.trim().length == 0) {
// when the user erases the searchText
this.dealerRepUserID = 0;
this.dealerRepChanging.emit(this.dealerRepUserID);
return EMPTY;
}
else if (this.dealerID == this.hostOrganizationID) {
// get a list of host reps
return this.myService.getHostRepsAutoComplete(searchText, this.includeInactive);
} else {
// get a list of dealer reps
return this.myService.getDealerReps(this.dealerID, searchText);
}
})
);
}
The function must return an Observable. How do I catch an error thrown inside the switchMap?
Have you try the catchError
import { catchError } from 'rxjs/operators';
return text$.pipe(
debounceTime(200),
distinctUntilChanged(),
// switchMap allows returning an observable rather than maps array
switchMap((searchText) => {
if (!searchText || searchText.trim().length == 0) {
// when the user erases the searchText
this.dealerRepUserID = 0;
this.dealerRepChanging.emit(this.dealerRepUserID);
return EMPTY;
}
else if (this.dealerID == this.hostOrganizationID) {
// get a list of host reps
return this.myService.getHostRepsAutoComplete(searchText, this.includeInactive).pipe(catchError(error => of());
} else {
// get a list of dealer reps
return this.myService.getDealerReps(this.dealerID, searchText).pipe(catchError(error => of());
}
})
);
Here is my app effect
public loadDataPerformance$: Observable<Action> = createEffect(() => {
return this.actions$.pipe(
ofType(RiskProfileActions.loadDataPerformance),
withLatestFrom(
this.store$.select(fromRoot.getAnalyticsFilterSelectedOptions),
this.store$.pipe(select(fromFactoryPerformance.getFactoryId))
),
switchMap(([{ recordDate }, filters, factoryId]) =>
this.riskProfileApiService.getDataPerformanceData(filters, factoryId, recordDate).pipe(
map((riskDataPerformanceData: PerformanceDataModel) =>
RiskProfileActions.loadRiskScoreBreakdownPerformanceSuccess(riskDataPerformanceData)
),
catchError(error => of(RiskProfileActions.loadRiskScoreBreakdownPerformanceFail(error)))
)
)
);
});
The switchMap by itself won't throw any error, the thing that might do something unexpected are the returned observables this.myService.getHostRepsAutoComplete and this.myService.getDealerReps. A tricky moment with the catching errors is that whenever there is an error the observable which is throwing the error is being killed.
For example
observable$.pipe(
switchMap(() => observable2$),
catchError(() => doSomethingFunction())
).subscribe()
observable$ will be completed once there is an error, that will complete your search stream and you will get no more data after the error.
As Phat Tran Ky showed in his example the handling of errors should happen inside the new streams in the switchMap operator
observable$.pipe(
switchMap(() => observable2$.pipe(catchError(() => doSomethingFunction())),
)
).subscribe()
By doing so whenever there is an error thrown from inside it will kill the inner observable (observable2$) but won't kill the outer subscriptions on the outer observable observable$
A further enhancement that you can do in order to handle your errors in one spot might be to merge the inner observable in one, for example, something like
observable$.pipe(
switchMap(() => {
return merge(
observable1$.pipe(filter(() => ${your if else condition for case 1})),
observable2$.pipe(filter(() => ${your if else condition for case 2})),
observable3$.pipe(filter(() => ${your if else condition for case 3})),
).pipe(catchError((error) => yourErrorHandlerFunction(error)))
})),
)
).subscribe()

Keeping error information and the outer observable alive

To ensure an error doesn't complete the outer observable, a common rxjs effects pattern I've adopted is:
public saySomething$: Observable<Action> = createEffect(() => {
return this.actions.pipe(
ofType<AppActions.SaySomething>(AppActions.SAY_SOMETHING),
// Switch to the result of the inner observable.
switchMap((action) => {
// This service could fail.
return this.service.saySomething(action.payload).pipe(
// Return `null` to keep the outer observable alive!
catchError((error) => {
// What can I do with error here?
return of(null);
})
)
}),
// The result could be null because something could go wrong.
tap((result: Result | null) => {
if (result) {
// Do something with the result!
}
}),
// Update the store state.
map((result: Result | null) => {
if (result) {
return new AppActions.SaySomethingSuccess(result);
}
// It would be nice if I had access the **error** here.
return new AppActions.SaySomethingFail();
}));
});
Notice that I'm using catchError on the inner observable to keep the outer observable alive if the underlying network call fails (service.saySomething(action.payload)):
catchError((error) => {
// What can I do with error here?
return of(null);
})
The subsequent tap and map operators accommodate this in their signatures by allowing null, i.e. (result: Result | null). However, I lose the error information. Ultimately when the final map method returns new AppActions.SaySomethingFail(); I have lost any information about the error.
How can I keep the error information throughout the pipe rather than losing it at the point it's caught?
As suggested in comments you should use Type guard function
Unfortunately I can't run typescript in snippet so I commented types
const { of, throwError, operators: {
switchMap,
tap,
map,
catchError
}
} = rxjs;
const actions = of({payload: 'data'});
const service = {
saySomething: () => throwError(new Error('test'))
}
const AppActions = {
}
AppActions.SaySomethingSuccess = function () {
}
AppActions.SaySomethingFail = function() {
}
/* Type guard */
function isError(value/*: Result | Error*/)/* value is Error*/ {
return value instanceof Error;
}
const observable = actions.pipe(
switchMap((action) => {
return service.saySomething(action.payload).pipe(
catchError((error) => {
return of(error);
})
)
}),
tap((result/*: Result | Error*/) => {
if (isError(result)) {
console.log('tap error')
return;
}
console.log('tap result');
}),
map((result/*: Result | Error*/) => {
if (isError(result)) {
console.log('map error')
return new AppActions.SaySomethingFail();
}
console.log('map result');
return new AppActions.SaySomethingSuccess(result);
}));
observable.subscribe(_ => {
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>
I wouldn't try to keep the error information throughout the pipe. Instead you should separate your success pipeline (tap, map) from your error pipeline (catchError) by adding all operators to the observable whose result they should actually work with, i.e. your inner observable.
public saySomething$: Observable<Action> = createEffect(() => {
return this.actions.pipe(
ofType<AppActions.SaySomething>(AppActions.SAY_SOMETHING),
switchMap((action) => this.service.saySomething(action.payload).pipe(
tap((result: Result) => {
// Do something with the result!
}),
// Update the store state.
map((result: Result) => {
return new AppActions.SaySomethingSuccess(result);
}),
catchError((error) => {
// I can access the **error** here.
return of(new AppActions.SaySomethingFail());
})
)),
);
});
This way tap and map will only be executed on success results from this.service.saySomething. Move all your error side effects and error mapping into catchError.

how to access previous mergeMap values from rxjs

I am learning to use RXJS. In this scenario, I am chaining a few async requests using rxjs. At the last mergeMap, I'd like to have access to the first mergeMap's params. I have explored the option using Global or withLatest, but neither options seem to be the right fit here.
const arraySrc$ = from(gauges).pipe(
mergeMap(gauge => {
return readCSVFile(gauge.id);
}),
mergeMap((csvStr: any) => readStringToArray(csvStr.data)),
map((array: string[][]) => transposeArray(array)),
mergeMap((array: number[][]) => forkJoin(uploadToDB(array, gauge.id))),
catchError(error => of(`Bad Promise: ${error}`))
);
readCSVFile is an async request which returns an observable to read CSV from a remote server.
readStringToArray is another async request which returns an observable to convert string to Arrays
transposeArray just does the transpose
uploadToDB is async DB request, which needs gague.id from the first mergeMap.
How do I get that? It would be great to take some advice on why the way I am doing it is bad.
For now, I am just passing the ID layer by layer, but it doesn't feel to be correct.
const arraySrc$ = from(gauges).pipe(
mergeMap(gauge => readCSVFile(gauge.id)),
mergeMap(({ data, gaugeId }: any) => readStringToArray(data, gaugeId)),
map(({ data, gaugeId }) => transposeArray(data, gaugeId)),
mergeMap(({ data, gaugeId }) => uploadToDB(data, gaugeId)),
catchError(error => of(`Bad Promise: ${error}`))
);
Why don't you do simply this?
const arraySrc$ = from(gauges).pipe(
mergeMap(gauge => readCSVFile(gauge.id).pipe(
mergeMap((csvStr: any) => readStringToArray(csvStr.data)),
map((array: string[][]) => transposeArray(array)),
mergeMap((array: number[][]) => forkJoin(uploadToDB(array, gauge.id)))
)),
catchError(error => of(`Bad Promise: ${error}`))
);
You can also wrap the inner observable in a function:
uploadCSVFilesFromGaugeID(gaugeID): Observable<void> {
return readCSVFile(gaugeID).pipe(
mergeMap((csvStr: any) => readStringToArray(csvStr.data)),
map((array: string[][]) => transposeArray(array)),
mergeMap((array: number[][]) => forkJoin(uploadToDB(array, gaugeID))
);
}
In order to do this at the end:
const arraySrc$ = from(gauges).pipe(
mergeMap(gauge => uploadCSVFileFromGaugeID(gauge.id)),
catchError(error => of(`Bad Promise: ${error}`))
);
MergeMap requires all observable inputs; else, previous values may be returned.
It is a difficult job to concatenate and display the merging response. But here is a straightforward example I made so you can have a better idea. How do we easily perform sophisticated merging.
async playWithBbservable() {
const observable1 = new Observable((subscriber) => {
subscriber.next(this.test1());
});
const observable2 = new Observable((subscriber) => {
subscriber.next(this.test2());
});
const observable3 = new Observable((subscriber) => {
setTimeout(() => {
subscriber.next(this.test3());
subscriber.complete();
}, 1000);
});
console.log('just before subscribe');
let result = observable1.pipe(
mergeMap((val: any) => {
return observable2.pipe(
mergeMap((val2: any) => {
return observable3.pipe(
map((val3: any) => {
console.log(`${val} ${val2} ${val3}`);
})
);
})
);
})
);
result.subscribe({
next(x) {
console.log('got value ' + x);
},
error(err) {
console.error('something wrong occurred: ' + err);
},
complete() {
console.log('done');
},
});
console.log('just after subscribe');
}
test1() {
return 'ABC';
}
test2() {
return 'PQR';
}
test3() {
return 'ZYX';
}

TypeError: You provided an invalid object where a stream was expected

The following code works. It does an ajax request and then call 2 actions, on at a time:
export const loadThingsEpic = action$ => {
return action$.ofType(LOAD_THINGS)
.mergeMap(({things}) => {
const requestURL = `${AppConfig.serverUrl()}/data/things`;
return ajax.getJSON(requestURL)).map(response => {
return finishLoadingThings(response);
}).map(() => {
return sendNotification('success');
});
})
.catch(e => {
return concat(of(finishLoadingThings({ things: {} })),
of(sendNotification('error')));
});
}}
But this code does not:
export const loadThingsEpic = action$ => {
return action$.ofType(LOAD_THINGS)
.mergeMap(({things}) => {
const requestURL = `${AppConfig.serverUrl()}/data/things`;
return ajax.getJSON(requestURL).switchMap(response => {
return concat(of(finishLoadingThings(response)),
of(sendNotification('success')));
});
})
.catch(e => {
return concat(of(finishLoadingThings({ things: {} })),
of(sendNotification('error')));
});
}
I've replace the map by a switchMap to merge 2 actions together (as seen in many other post). It works in the catch if an exception is thrown. I'm wondering whats wrong with the code. I'm guessing it's because I can't seem to really grasp when to use: map, swicthMap and mergeMap.
sendNotification and finishLoadingthings returns action object:
export function finishLoadingThings(data: any) {
return {
type: FINISH_LOADING_THINGS,
data,
};
}
Thanks!
The code provided as-is appears to work as intended: https://jsbin.com/becapin/edit?js,console I do not receive a "invalid object where stream expected" error when the ajax succeeds or fails.
Are you sure the error is coming from this code?
On a separate note, you might be happy to hear that Observable.of supports an arbitrary number of arguments, each one will be emitted after the other. So instead of this:
.switchMap(response => {
return concat(of(finishLoadingThings(response)),
of(sendNotification('success')));
});
You can just do this:
.switchMap(response => {
return of(
finishLoadingThings(response),
sendNotification('success')
);
});
This would not have caused a bug though, it's just cleaner.
I manage to fix my problem, by doing the switchMap at the same level than the mergeMap. Like this:
export const loadThingsEpic = action$ => {
return action$.ofType(LOAD_THINGS)
.mergeMap(({things}) => {
const requestURL = `${AppConfig.serverUrl()}/data/things`;
return ajax.getJSON(requestURL).switchMap(response => {
return of(response);
});
})
.switchMap((res) => {
return concat(of(finishLoadingThings(res.value)),
of(sendNotification('success')));
})
.catch(e => {
return concat(of(finishLoadingThings({ things: {} })),
of(sendNotification('error')));
});
}
Don't quite get it yet.

ECMAScript 6 Chaining Promises

I'm trying to chain promises, but the second one doesn't call the resolve function. What do I do wrong?
function getCustomers(){
let promise = new Promise((resolve, reject) => {
console.log("Getting customers");
// Emulate an async server call here
setTimeout(() => {
var success = true;
if (success) {
resolve( "John Smith"); // got the customer
} else {
reject("Can't get customers");
}
}, 1000);
}
);
return promise;
}
function getOrders(customer) {
let promise = new Promise((resolve, reject) => {
console.log("Getting orders");
// Emulate an async server call here
setTimeout(() => {
var success = true;
if (success) {
resolve("Order 123"); // got the order
} else {
reject("Can't get orders");
}
}, 1000);
}
);
return promise;
}
getCustomers()
.then((cust) => getOrders(cust))
.catch((err) => console.log(err));
console.log("Chained getCustomers and getOrders. Waiting for results");
The code prints "Getting orders" from the second function, but doesn't print "Order 123":
Getting customers
Chained getCustomers and getOrders. Waiting for results
Getting orders
Update. I wanted to insert the print on the console between chained methods that return promises. I guess something like this is not possible:
getCustomers()
.then((cust) => console.log(cust)) //Can't print between chained promises?
.then((cust) => getOrders(cust))
.then((order) => console.log(order))
.catch((err) => console.error(err));
You want to chain a success handler (for your resolve result "Order 123"), not an error handler. So use then instead of catch :-)
getCustomers()
.then(getOrders)
.then((orders) => console.log(orders))
.catch((err) => console.error(err));
None of the promises was rejected, so the console.log(err) in your code was never called.
I wanted to insert the print on the console between chained methods that return promises. I guess something like this is not possible:
getCustomers()
.then((cust) => console.log(cust)) //Can't print between chained promises?
.then((cust) => getOrders(cust))
Yes it is possible, but you are intercepting a chain here. So the second then callback actually is not called with cust, but with the result of the first then callback - and console.log returns undefined, with which getOrders will get some problems.
You'd either do
var customers = getCustomers();
customers.then(console.log);
customers.then(getOrders).then((orders) => …)
or simpler just
getCustomers()
.then((cust) => { console.log(cust); return cust; })
.then(getOrders)
.then((orders) => …)
Here is a code example for Sequential execution for node.js using ES6 ECMAScript. Maybe somebody finds it useful.
http://es6-features.org/#PromiseUsage
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
var soapClient = easysoap.createClient(params);
//Sequential execution for node.js using ES6 ECMAScript
console.log('getAllFunctions:');
soapClient.getAllFunctions()
.then((functionArray) => {
return new Promise((resolve, reject) => {
console.log(functionArray);
console.log('getMethodParamsByName:');
resolve();
});
})
.then(() => {
return soapClient.getMethodParamsByName('test1'); //will return promise
})
.then((methodParams) => {
console.log(methodParams.request); //Console log can be outside Promise like here too
console.log(methodParams.response);
console.log('call');
return soapClient.call({ //Return promise
method: 'test1',
params: {
myArg1: 'aa',
myArg2: 'bb'
}
});
})
.then((callResponse) => {
console.log(callResponse); // response data as json
console.log('end');
})
.catch((err) => {
throw new Error(err);
});

Resources