I have implemented data validation and sanitization in my Branch class, but I am concerned about the repetition in my code. I feel like I may be using custom errors excessively by creating one for each situation.
I would appreciate some suggestions on how to adhere to the DRY principle in this code and create reusable custom errors.
import {Column, Entity, ManyToOne, PrimaryGeneratedColumn} from "typeorm";
import {SystemModule} from "../../enums/SystemModule.enum";
import {Environment} from "../Environment.entity";
import {ZipCode} from "../../value-objects/ZipCode/ZipCode.value-object";
import {Cnpj} from "../../value-objects/Cnpj/Cnpj.value-object";
import {NameLengthCannotBeZeroException} from "./exceptions/NameLengthCannotBeZero.exception";
import {NameLengthCannotBeAbove200Exception} from "./exceptions/NameLengthCannotBeAbove200.exception";
// Other exception imports...
@Entity("branches")
export class Branch {
// Class properties here...
private static sanitizeAndValidateProperty(value: string | number | null, maxLength: number, exceptionType: any) {
const sanitizedValue = String(value).split("\n")[0]
.replace(/^[\r\t\f ]+|[\r\t\f ]+$/g, "")
.replace(/[\t\f ]+/g, " ");
if (sanitizedValue.length > maxLength) {
throw new exceptionType();
}
return sanitizedValue;
}
// Methods to sanitize and validate different entity properties...
}