Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  21] [ 4]  / answers: 1 / hits: 65694  / 6 Years ago, wed, may 23, 2018, 12:00:00

I am using Angular and TypeScript.
I have used try catch construct for error handling in case of API call.
If any error occurs in try block it is simply NOT going to catch block.
App terminates there only.



I have tried using throw as well.
Here is a sample code snippet,



try {

this.api.getAPI(Id).subscribe( // this.api is my api service and getAPI is present there
(data: any) => {
if (data == null) {
throw 'Empty response';
}
},
(error: HttpErrorResponse) => {
console.log(error);
};

} catch(e) {
console.log(e);
}


in some cases 'data' from API returns 'null',
but throw is not going to catch block
ALSO, tried without throw, it gives null error for 'data' ... in that case also not going to catch block.


More From » rxjs

 Answers
33

A try/catch won't catch anything in a callback passed to subscribe (or then, or setTimeout or anything smiilar) which runs on a different tick or microtask. You have to catch errors in the task where they occurred.



I could suggest better alternatives if I understood what you were trying to do when the error occurred. If all you really want to do is to log it, you could of course do that right after the check for null.



You might consider mapping the observable prior to consuming it and issuing an error on the observable in case of a null, such as:



const checkedData = this.api.getAPI(Id).pipe(map(data => {
if (data === null) return throwError(null data);
return data;
});


Now you can subscribe with



checkedData.subscribe(
data => /* do something with data */,
console.error
);


Note: throwError is rxjs6. For rxjs5, it would be return ErrorObservable(null data) (I think).


[#54364] Sunday, May 20, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaleyv

Total Points: 259
Total Questions: 99
Total Answers: 107

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;