Angular2 ExceptionHandler - 检查错误对象是否为响应

时间:2016-07-21 00:53:31

标签: javascript angularjs angular

我目前正在使用以下代码来处理异常:

@Injectable()
export class CustomExceptionHandler extends ExceptionHandler {
call(error, stackTrace = null, reason = null) {
    console.warn(error);
}

代码工作正常,我可以在控制台中看到错误。错误是一个Response对象,在@ angular / core中定义。但是,错误参数是“any”。我无法更改错误类型(例如错误:响应),因为它不一定是Response对象,它可以是任何东西。

我想使用(error instanceof Response),但这不起作用,因为错误是一种对象,这是有道理的。

更新

事实证明(error instanceof Response)确实有效。出于某种原因,当您使用VS Code调试打字稿时,它似乎不起作用。我把手表放在上面它总是假的。也许是因为我没有在运行时检查

无论如何,重要的是在Angular2 Response对象的上下文中,instanceof可以正常工作,因为它们有一个构造函数

感谢@DanSimon帮助缩小出错的范围,并提供其他方法来检查对象的类型!

1 个答案:

答案 0 :(得分:1)

有趣的问题。由于TypeScript实际上只是编译为JS,因此类并不存在。我可以想到两种可以检查的方法,你可以使用“用户定义的类型保护”或使用“instanceof type guard”。用户定义的类型保护只是检查对象的属性/功能以确定其类型的一种奇特方式,优点是TS不会抱怨“缺少属性/功能”。使用“instanceof”有效但仅当Object具有构造函数时,因为它比较了两个Object的构造函数。因此,如果你的Object没有构造函数,那就不行了。您可以找到这两个here的文档。

我还制作了一个plunker来证明它们是如何工作的。结果将加载到控制台中,因此请使用浏览器调试工具查看结果。所有工作都在“ngOnChanges”函数的“app / child.component.ts”上完成。

ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
  console.log();
  console.log("Custom function isSimpleChange:", this.isSimpleChange(changes));
  console.log("Using instanceof SimpleChange:", (changes instanceof SimpleChange));
  console.log("Using Object.prototype.toString.call():", Object.prototype.toString.call(changes));
  console.log("Logging the object itself:",changes);
  console.log("-----------------------------------------------------------------------------------------");
  let testExample = new ExampleObject();
  console.log("Custom function isExampleObject:", this.isExampleObject(testExample));
  console.log("Using instanceof ExampleObject:", (testExample instanceof ExampleObject));
  console.log("Using Object.prototype.toString.call():" + Object.prototype.toString.call(testExample));
  console.log(testExample);


  this._result = changes.value.currentValue;
  this._changes++;
}

您可能需要利用两者以及原始类型的“typeof”来对对象进行全面检查。所以使用“typeof”检查基本类型“string”,“number”,“boolean”。然后使用“instanceof”查看构造函数是否匹配,最后使用“User-Defined Type Guard”查找特定的“属性/函数”。

相关问题