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,14 +905,35 @@ 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,
messageBody,
messageBodyForRetry,
'createMessage',
(newConvId) => doCreateMessage(newConvId),
);
}
}
private async handleStaleConversationError(
error: any,
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 bodyForRetry = messageBodyForRetry || messageBody;
if (!bodyForRetry) { if (!bodyForRetry || !bodyForRetry.key?.remoteJid) {
this.logger.error('Cannot retry createMessage without a message body for context.'); this.logger.error(`Cannot retry ${functionName} without a message body for context.`);
return null; return null;
} }
@ -922,18 +943,17 @@ export class ChatwootService {
const newConversationId = await this.createConversation(instance, bodyForRetry); const newConversationId = await this.createConversation(instance, bodyForRetry);
if (!newConversationId) { if (!newConversationId) {
this.logger.error(`Failed to create new conversation for ${remoteJid}`); this.logger.error(`Failed to create new conversation for ${remoteJid} during retry.`);
return null; return null;
} }
this.logger.log(`Retrying message creation for ${remoteJid} with new conversation ${newConversationId}`); this.logger.log(`Retrying ${functionName} for ${remoteJid} with new conversation ${newConversationId}`);
return await doCreateMessage(newConversationId); return await originalFunction(newConversationId);
} else { } else {
this.logger.error(`Error creating message: ${error}`); this.logger.error(`Error in ${functionName}: ${error}`);
throw error; throw error;
} }
} }
}
public async getOpenConversationByContact( public async getOpenConversationByContact(
instance: InstanceDto, instance: InstanceDto,
@ -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;
}
} }
} }