简体   繁体   中英

TypeScript/Angular try catch, any error in try block not going to catch block

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM