你好,我正在尝试自定义错误,我开始犯基本错误,但是我在接口和类型方面遇到了问题
这是我的代码:
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
答案 0 :(得分:0)
下面是还原错误的简化代码:
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
}
}