你好,我想做一个自定义的错误,我开始做一个基础错误,但我在接口和类型上有问题。
这是我的代码。
export interface errors_fields {
field: string;
code: string;
}
export interface configError {
type?: string;
message?: string;
code?: number;
errors?: object[] | null | errors_fields | errors_fields[];
internalData?: object;
options?: {
showPath?: boolean;
showLocations?: boolean;
};
}
export class BaseError extends ExtendableError {
type: string;
message: string;
code: number;
errors: object[] | null | errors_fields | errors_fields[];
internalData: object;
path: any;
locations: any;
_showLocations: boolean = false;
_showPath: boolean = false;
constructor(configError: configError) {
super((configError && configError.message) || '');
const type = configError.type;
const message = configError.message;
const code = configError.code;
const errors = configError.errors;
const internalData = configError.internalData;
const options = configError.options;
this.type = type;
this.message = message;
this.code = code;
this.errors = errors;
this.internalData = internalData;
this._showLocations = !options.showLocations;
this._showPath = !options.showPath;
}
serialize(): configError {
const { type, message, code, errors, path, locations } = this;
let error: configError = {
type,
message,
code,
errors,
};
return error;
}
}
export const isInstance = (e) => e instanceof BaseError;
export class UnprocessableEntityERROR extends BaseError {
constructor(errors: errors_fields[]) {
super(errors);
this.type = 'Unprocessable Entity';
this.message = 'Validation Failed';
this.code = 422;
this.errors = errors;
}
}
然后用这个抛出错误。
let validationErrors: InputErrors[] = [];
let user = await this.userRep.findOne({ where: { email: data.email } });
//email length
if (!(data.email.length > 1 && data.email.length < 250)) {
validationErrors.push({ field: 'email', code: 'invalid_field' });
}
if (!(data.name.length > 1 && data.name.length < 250)) {
validationErrors.push({ field: 'name', code: 'invalid_field' });
}
throw new UnprocessableEntityERROR(validationErrors);
但我的UnprocessableEntity类的构造函数有问题,基本上我只会收到错误(有错误的字段)。
我得到了这个错误。
类型' errors_fields[]'与类型'configError'.ts(255)没有共同属性。
在我的UnprocessableEntityERROR上
下面是一个还原的代码,重现了这个错误。
export interface errors_fields {
field: string;
}
export interface configError {
type: string;
}
export class BaseError {
constructor(configError: configError) {
}
}
export class UnprocessableEntityERROR extends BaseError {
constructor(errors: errors_fields[]) {
super(errors); // Incompatible
}
}
你之所以会出现这个错误是因为 errors_fields[]
不能传递给 BaseError
构造函数。你需要传递一个 configError
.
创建一个 configError
在你的超级电话中,例如
export interface errors_fields {
field: string;
}
export interface configError {
type: string;
}
export class BaseError {
constructor(configError: configError) {
}
}
export class UnprocessableEntityERROR extends BaseError {
constructor(errors: errors_fields[]) {
super({type: 'something'}); // OKAY
}
}