// Définition de l'erreur d'adapter dans la couche infrastructure
class AdapterError extends Error {
constructor(
message: string,
public readonly field?: string,
public readonly value?: any
) {
super(message);
this.name = "AdapterError";
}
}
// Utilisation dans un adapter
class OrderAdapter {
static dtoToOrderEntity(dto: OrderDTO): Order {
try {
if (!dto) {
throw new AdapterError("DTO de commande invalide");
}
// Transformation avec validation
return new Order({
id: dto.id,
items: this.mapItems(dto.items),
customer: this.mapCustomer(dto.customer),
});
} catch (error) {
// Si c'est déjà une AdapterError, on la relance
if (error instanceof AdapterError) {
throw error;
}
// Sinon, on l'enveloppe avec plus de contexte
throw new AdapterError(
`Erreur lors de la transformation de la commande: ${error.message}`
);
}
}
private static mapItems(items: any[]): OrderItem[] {
if (!Array.isArray(items)) {
throw new AdapterError(
"Les items doivent être un tableau",
"items",
items
);
}
return items.map((item, index) => {
if (!item) {
throw new AdapterError(
`Item invalide à l'index ${index}`,
`items[${index}]`,
item
);
}
return DtoItemAdapter.dtoToItemEntity(item);
});
}
private static mapCustomer(customer: any): Customer | undefined {
if (!customer) {
return undefined;
}
return DtoCustomerAdapter.dtoToCustomerEntity(customer);
}
}