TypeScript / Angular try catch,try块中的任何错误都不会捕获块 [英] TypeScript/Angular try catch, any error in try block not going to catch block

查看:1302
本文介绍了TypeScript / Angular try catch,try块中的任何错误都不会捕获块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular和TypeScript。
我在API调用的情况下使用了try catch构造来进行错误处理。
如果在try块中发生任何错误,它就不会捕获块。
应用只在那里终止。

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.

我也试过使用 throw
下面是一个示例代码段,

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); 
}

在某些情况下,来自API的数据返回'null',
但是throw不会捕获块
ALSO,尝试不抛出,它为'data'提供null错误。在这种情况下也不会阻止阻塞。

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 将不会捕获传递给 subscribe (或然后的回调中的任何内容> setTimeout 或任何smiilar)在不同的tick或microtask上运行。你必须在任务中捕获错误发生了。

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.

如果我理解错误发生时你想要做什么,我可以建议更好的选择。如果您真正想做的就是记录它,当然可以在检查null之后立即执行此操作。

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.

您可以考虑在使用它之前映射observable如果为null,则在observable上发出错误,例如:

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;
});

现在您可以订阅

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

注意: throwError 是rxjs6。对于rxjs5,它将是返回ErrorObservable (空数据)(我认为)。

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

这篇关于TypeScript / Angular try catch,try块中的任何错误都不会捕获块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆