Javascript TypeScript/Angular try catch,try 块中的任何错误都不会捕获块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/50490176/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript/Angular try catch, any error in try block not going to catch block
提问by Nils
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.
我正在使用 Angular 和 TypeScript。我已经使用 try catch 构造在 API 调用的情况下进行错误处理。如果在 try 块中发生任何错误,它就不会捕获块。应用程序仅在那里终止。
I have tried using throwas well. 
Here is a sample code snippet,
我也试过使用throw。这是一个示例代码片段,
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.
在某些情况下,来自 API 的“数据”返回“空”,但 throw 也不会捕获块,尝试不抛出,它会为“数据”提供空错误……在这种情况下,也不会捕获块。
回答by
A try/catchwon't catch anything in a callback passed to subscribe(or then, or setTimeoutor anything smiilar) which runs on a different "tick" or "microtask". You have to catch errors in the task where they occurred. 
Atry/catch不会在传递给subscribe(或then,setTimeout或任何类似的)的回调中捕获任何在不同“滴答”或“微任务”上运行的回调中的任何内容。您必须在发生错误的任务中捕获错误。
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.
如果我了解您在发生错误时要执行的操作,我可以提出更好的替代方案。如果您真正想要做的只是记录它,您当然可以在检查 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:
您可能会考虑在使用 observable 之前映射它,并在为 null 的情况下在 observable 上发出错误,例如:
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: throwErroris rxjs6. For rxjs5, it would be return ErrorObservable("null data")(I think).
注意:throwError是 rxjs6。对于 rxjs5,它将是return ErrorObservable("null data")(我认为)。

