我想扩展类Error并能够通过类似于此的一些调用返回自定义错误:
throw new Error('MessageGoesHere', ObjectWithOtherResultGoesHere | or NULL, ErrorCode);
例如......让我们说我们有一个像下面这样的方法(我做了):
public getInformation(value1: string, value2:string): Promise<MyDataResponse> {
const promise = this.callFunction2(value1, value2)
.then(result => {
return result;
})
.catch(error => {
MyDataResponse errorResponse = {
field1: value1,
field2: value2
};
throw new CustomError('Error getting information', errorResponse, 003);
});
return Promise.resolve(promise);
}
我想用三个字段抛出自己的CustomError。为此,我创建了以下类:
export default class CustomError extends Error {
constructor (message: string, newResultObject: object, status: number) {
// Calling parent constructor of base Error class.
super(message);
// Saving class name in the property of our custom error as a shortcut.
this.name = this.constructor.name;
// Capturing stack trace, excluding constructor call from it.
Error.captureStackTrace(this, this.constructor);
status = status || 500;
newResultObject = newResultObject;
}
}
但是,我无法执行 this.status 或 this.newResultObject ,因为它们不属于Error类,所以它永远不会返回值。那么我该如何创建CustomError类呢?我应该从不同的错误扩展吗?
答案 0 :(得分:1)
您的班级正在定义status
和newResultObject
属性,因此您只需设置它们即可。
你只需要改变
status = status || 500;
newResultObject = newResultObject;
到
this.status = status || 500;
this.newResultObject = newResultObject;
你班上的