无法检查捕获的Typescript自定义错误的类型
我创建了一个自定义typescript错误,它基于几个来源,如下所示:无法检查捕获的Typescript自定义错误的类型,typescript,typescript1.8,Typescript,Typescript1.8,我创建了一个自定义typescript错误,它基于几个来源,如下所示: export class Exception extends Error { constructor(public message: string) { super(message); this.name = 'Exception'; this.message = message; this.stack = (<any>new Error(
export class Exception extends Error {
constructor(public message: string) {
super(message);
this.name = 'Exception';
this.message = message;
this.stack = (<any>new Error()).stack;
}
toString() {
return this.name + ': ' + this.message;
}
}
export class SpecificException extends Exception {
}
在其他地方我发现了:
catch (e) {
var t1 = Object.getPrototypeOf(e);
var t2 = SpecificException.prototype;
if (e instanceof SpecificException) {
console.log("as expected");
}
else {
console.log("not as expected");
}
}
此代码打印“不符合预期”。你知道为什么吗
以后编辑
正如@basarat在下面指出的,错误是预期的类型。经过进一步调查,我意识到这是由于模块重复与我的环境有关,可能是因为在观看模式下使用摩卡 运行了以下代码:
declare global {
interface Error {
stack: any;
}
}
class Exception extends Error {
constructor(public message: string) {
super(message);
this.name = 'Exception';
this.message = message;
this.stack = (<any>new Error()).stack;
}
toString() {
return this.name + ': ' + this.message;
}
}
class SpecificException extends Exception {
}
try {
throw new SpecificException('foo');
}
catch (e) {
var t1 = Object.getPrototypeOf(e);
var t2 = SpecificException.prototype;
if (e instanceof SpecificException) {
console.log("as expected");
}
else {
console.log("not as expected");
}
}
因此,在询问的问题中没有发布错误运行以下代码:
declare global {
interface Error {
stack: any;
}
}
class Exception extends Error {
constructor(public message: string) {
super(message);
this.name = 'Exception';
this.message = message;
this.stack = (<any>new Error()).stack;
}
toString() {
return this.name + ': ' + this.message;
}
}
class SpecificException extends Exception {
}
try {
throw new SpecificException('foo');
}
catch (e) {
var t1 = Object.getPrototypeOf(e);
var t2 = SpecificException.prototype;
if (e instanceof SpecificException) {
console.log("as expected");
}
else {
console.log("not as expected");
}
}
所以问题中没有错误,你确定吗?对我来说,
e instanceof Exception
和e instanceof specific Exception
都是真的。你确定吗?对我来说,e instanceof Exception
和e instanceof specific Exception
都是真的。
as expected