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

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

问题描述

我正在使用 Angular 和 TypeScript.我已经使用 try catch 构造在 API 调用的情况下进行错误处理.如果 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 的数据"返回空",但 throw 不会捕获块另外,尝试不抛出,它会为数据"提供空错误......在这种情况下也不会捕获块.

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.

推荐答案

try/catch 不会在传递给 subscribe(或 >thensetTimeout 或任何类似的)在不同的tick"或微任务"上运行.您必须在发生错误的任务中捕获错误.

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,它将是 return ErrorObservable("null data")(我认为).

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

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

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