refactor(chatbot): melhorar tratamento de erros em mensagens no Chatwoot

- Implementada a função `handleStaleConversationError` para centralizar a lógica de tratamento de erros relacionados a conversas não encontradas.
- A lógica de retry foi aprimorada para as funções `createMessage` e `sendData`, garantindo que as operações sejam reprocessadas corretamente em caso de falhas.
- Removido código duplicado e melhorada a legibilidade do serviço Chatwoot.
This commit is contained in:
Vitordotpy 2025-09-25 17:38:10 -03:00
parent 8697329f71
commit 5dc1d02d0a

View File

@ -905,33 +905,53 @@ export class ChatwootService {
try { try {
return await doCreateMessage(conversationId); return await doCreateMessage(conversationId);
} catch (error) { } catch (error) {
const errorMessage = error.toString().toLowerCase(); return this.handleStaleConversationError(
const status = error.response?.status; error,
if (errorMessage.includes('not found') || status === 404) { instance,
this.logger.warn(`Conversation ${conversationId} not found. Retrying...`); conversationId,
const bodyForRetry = messageBodyForRetry || messageBody; messageBody,
messageBodyForRetry,
'createMessage',
(newConvId) => doCreateMessage(newConvId),
);
}
}
if (!bodyForRetry) { private async handleStaleConversationError(
this.logger.error('Cannot retry createMessage without a message body for context.'); error: any,
return null; instance: InstanceDto,
} conversationId: number,
messageBody: any,
messageBodyForRetry: any,
functionName: string,
originalFunction: (newConversationId: number) => Promise<any>,
) {
if (axios.isAxiosError(error) && error.response?.status === 404) {
this.logger.warn(
`Conversation ${conversationId} not found in Chatwoot. Retrying operation from ${functionName}...`,
);
const bodyForRetry = messageBodyForRetry || messageBody;
const {remoteJid} = bodyForRetry.key; if (!bodyForRetry || !bodyForRetry.key?.remoteJid) {
const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`; this.logger.error(`Cannot retry ${functionName} without a message body for context.`);
await this.cache.delete(cacheKey); return null;
const newConversationId = await this.createConversation(instance, bodyForRetry);
if (!newConversationId) {
this.logger.error(`Failed to create new conversation for ${remoteJid}`);
return null;
}
this.logger.log(`Retrying message creation for ${remoteJid} with new conversation ${newConversationId}`);
return await doCreateMessage(newConversationId);
} else {
this.logger.error(`Error creating message: ${error}`);
throw error;
} }
const { remoteJid } = bodyForRetry.key;
const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`;
await this.cache.delete(cacheKey);
const newConversationId = await this.createConversation(instance, bodyForRetry);
if (!newConversationId) {
this.logger.error(`Failed to create new conversation for ${remoteJid} during retry.`);
return null;
}
this.logger.log(`Retrying ${functionName} for ${remoteJid} with new conversation ${newConversationId}`);
return await originalFunction(newConversationId);
} else {
this.logger.error(`Error in ${functionName}: ${error}`);
throw error;
} }
} }
@ -1086,34 +1106,15 @@ export class ChatwootService {
try { try {
return await doSendData(conversationId); return await doSendData(conversationId);
} catch (error) { } catch (error) {
const errorMessage = error.toString().toLowerCase(); return this.handleStaleConversationError(
const status = error.response?.status; error,
instance,
if (errorMessage.includes('not found') || status === 404) { conversationId,
this.logger.warn(`Conversation ${conversationId} not found. Retrying...`); messageBody,
const bodyForRetry = messageBodyForRetry || messageBody; messageBodyForRetry,
'sendData',
if (!bodyForRetry) { (newConvId) => doSendData(newConvId),
this.logger.error('Cannot retry sendData without a message body for context.'); );
return null;
}
const {remoteJid} = bodyForRetry.key;
const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`;
await this.cache.delete(cacheKey);
const newConversationId = await this.createConversation(instance, bodyForRetry);
if (!newConversationId) {
this.logger.error(`Failed to create new conversation for ${remoteJid}`);
return null;
}
this.logger.log(`Retrying sendData for ${remoteJid} with new conversation ${newConversationId}`);
return await doSendData(newConversationId);
} else {
this.logger.error(error);
return null;
}
} }
} }