[英]Angular2 ExceptionHandler - check if error object is Response
我目前正在使用以下代码来处理异常:
@Injectable()
export class CustomExceptionHandler extends ExceptionHandler {
call(error, stackTrace = null, reason = null) {
console.warn(error);
}
该代码工作正常,我可以在控制台中看到错误。 错误是在@ angular / core中定义的Response对象。 但是,错误参数为“ any”。 我不能更改错误类型(例如error:Response),因为它不一定是Response对象,可以是任何东西。
我想使用(Error instanceof Response),但是那行不通,因为错误是一种对象,这很有意义。
更新
因此,事实证明(error instanceof Response)
确实可以工作。 由于某些原因,当您使用VS Code调试打字稿时,它似乎不起作用。 我放了一块手表,它总是返回false。 也许是因为我没有在运行时检查
无论如何,重要的是,在Angular2 Response对象的上下文中, instanceof
可以正常工作,因为它们确实具有构造函数
感谢@DanSimon帮助缩小问题范围,并提供其他方法来检查对象的类型!
有趣的问题。 由于TypeScript实际上只是编译为JS,所以类实际上并不存在。 我可以想到两种检查方法,可以使用“用户定义的类型防护”或“实例类型的防护”。 用户定义的类型防护只是检查对象的属性/功能以确定其类型的一种好方法,优点是TS不会抱怨“缺少属性/功能”。 仅当对象具有构造函数时才使用“ instanceof”,因为它在比较两个对象的构造函数。 因此,如果您的对象没有构造函数,那是不可行的。 您可以在此处找到这两个文档。
我还制作了一个小插曲,演示了它们如何工作。 结果将加载到控制台中,因此请使用浏览器调试工具查看结果。 所有工作都在“ 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”查找特定的“ properties / functions”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.