Typescript出现了instanceof checks on custom errors问题,但尚不清楚我们需要做什么来使instanceof
工作。例如,对于该异常,我们将如何使instanceof
工作:
/**
* @param message The error message
* @param value The value that violates the constraint
* @param field The name of the field
* @param type The expected type for the field
* @param constraint The name of the constraint violated
* @param code The application or module code for the error
*/
export class IsError extends Error {
constructor(
public message:string,
public value: any,
public field?:string,
public type?: string,
public constraint?: string,
public code?:string) {
super(message);
this.name = 'IsError';
Object.setPrototypeOf(this, IsError.prototype);
}
}
This link says we can manually adjust the prototype,这是我正在做的,但是此测试未通过:
it("should be an instance of IsError", () => {
let error = new IsError("This is an IsError", 'value');
expect(error instanceof IsError)).toBeTruthy();
});
我在测试...IsError))
中有一个附加括号,我误认为该测试未通过。我更新了测试,现在可以正常工作了。因此,此问题中的示例IsError
实现是正确的。
IIUC的这种实现在ES5中不起作用,但是包括CoreJS的AFAIK客户端也可以。
答案 0 :(得分:3)
/**
* Base Error.
*/
class BaseError extends Error {
constructor(message?: string) {
const trueProto = new.target.prototype;
super(message);
Object.setPrototypeOf(this, trueProto);
}
}
class Err1 extends BaseError {}
const e1 = new Err1();
console.log(e1 instanceof Err1); // true
console.log(e1 instanceof Error); // true
class Err2 extends Err1 {}
const e2 = new Err2();
console.log(e2 instanceof Err1); // true
console.log(e2 instanceof Err2); // true
console.log(e2 instanceof Error); // true
class NoBaseErr extends Error {}
const x = new NoBaseErr();
console.log(x instanceof Error); // true
console.log(x instanceof NoBaseErr); // false !!!
import BaseError from 'ts-base-error';
答案 1 :(得分:1)
AFAIK,{6}是Object.setPrototypeOf()
-ref
TypeScript#13965中的这段代码对我有效(在es5中)
export class MyError extends Error {
__proto__: Error;
constructor(message?: string) {
const trueProto = new.target.prototype;
super(message);
// Alternatively use Object.setPrototypeOf if you have an ES6 environment.
this.__proto__ = trueProto;
}
}
答案 2 :(得分:1)
代码中出了什么问题(如您正确指出的那样)是断言中的附加括号。
为了完整起见,一个可行的最小示例如下:
class CustomError extends Error {
constructor() {
super();
Object.setPrototypeOf(this, CustomError.prototype);
}
}
let error = new CustomError();
console.log(error instanceof CustomError); // Will log 'true'