Skip to content

Commit 5dc1d02

Browse files
committed
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.
1 parent 8697329 commit 5dc1d02

File tree

1 file changed

+52
-51
lines changed

1 file changed

+52
-51
lines changed

src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts

Lines changed: 52 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -905,33 +905,53 @@ export class ChatwootService {
905905
try {
906906
return await doCreateMessage(conversationId);
907907
} catch (error) {
908-
const errorMessage = error.toString().toLowerCase();
909-
const status = error.response?.status;
910-
if (errorMessage.includes('not found') || status === 404) {
911-
this.logger.warn(`Conversation ${conversationId} not found. Retrying...`);
912-
const bodyForRetry = messageBodyForRetry || messageBody;
913-
914-
if (!bodyForRetry) {
915-
this.logger.error('Cannot retry createMessage without a message body for context.');
916-
return null;
917-
}
908+
return this.handleStaleConversationError(
909+
error,
910+
instance,
911+
conversationId,
912+
messageBody,
913+
messageBodyForRetry,
914+
'createMessage',
915+
(newConvId) => doCreateMessage(newConvId),
916+
);
917+
}
918+
}
918919

919-
const {remoteJid} = bodyForRetry.key;
920-
const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`;
921-
await this.cache.delete(cacheKey);
920+
private async handleStaleConversationError(
921+
error: any,
922+
instance: InstanceDto,
923+
conversationId: number,
924+
messageBody: any,
925+
messageBodyForRetry: any,
926+
functionName: string,
927+
originalFunction: (newConversationId: number) => Promise<any>,
928+
) {
929+
if (axios.isAxiosError(error) && error.response?.status === 404) {
930+
this.logger.warn(
931+
`Conversation ${conversationId} not found in Chatwoot. Retrying operation from ${functionName}...`,
932+
);
933+
const bodyForRetry = messageBodyForRetry || messageBody;
922934

923-
const newConversationId = await this.createConversation(instance, bodyForRetry);
924-
if (!newConversationId) {
925-
this.logger.error(`Failed to create new conversation for ${remoteJid}`);
926-
return null;
927-
}
935+
if (!bodyForRetry || !bodyForRetry.key?.remoteJid) {
936+
this.logger.error(`Cannot retry ${functionName} without a message body for context.`);
937+
return null;
938+
}
928939

929-
this.logger.log(`Retrying message creation for ${remoteJid} with new conversation ${newConversationId}`);
930-
return await doCreateMessage(newConversationId);
931-
} else {
932-
this.logger.error(`Error creating message: ${error}`);
933-
throw error;
940+
const { remoteJid } = bodyForRetry.key;
941+
const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`;
942+
await this.cache.delete(cacheKey);
943+
944+
const newConversationId = await this.createConversation(instance, bodyForRetry);
945+
if (!newConversationId) {
946+
this.logger.error(`Failed to create new conversation for ${remoteJid} during retry.`);
947+
return null;
934948
}
949+
950+
this.logger.log(`Retrying ${functionName} for ${remoteJid} with new conversation ${newConversationId}`);
951+
return await originalFunction(newConversationId);
952+
} else {
953+
this.logger.error(`Error in ${functionName}: ${error}`);
954+
throw error;
935955
}
936956
}
937957

@@ -1086,34 +1106,15 @@ export class ChatwootService {
10861106
try {
10871107
return await doSendData(conversationId);
10881108
} catch (error) {
1089-
const errorMessage = error.toString().toLowerCase();
1090-
const status = error.response?.status;
1091-
1092-
if (errorMessage.includes('not found') || status === 404) {
1093-
this.logger.warn(`Conversation ${conversationId} not found. Retrying...`);
1094-
const bodyForRetry = messageBodyForRetry || messageBody;
1095-
1096-
if (!bodyForRetry) {
1097-
this.logger.error('Cannot retry sendData without a message body for context.');
1098-
return null;
1099-
}
1100-
1101-
const {remoteJid} = bodyForRetry.key;
1102-
const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`;
1103-
await this.cache.delete(cacheKey);
1104-
1105-
const newConversationId = await this.createConversation(instance, bodyForRetry);
1106-
if (!newConversationId) {
1107-
this.logger.error(`Failed to create new conversation for ${remoteJid}`);
1108-
return null;
1109-
}
1110-
1111-
this.logger.log(`Retrying sendData for ${remoteJid} with new conversation ${newConversationId}`);
1112-
return await doSendData(newConversationId);
1113-
} else {
1114-
this.logger.error(error);
1115-
return null;
1116-
}
1109+
return this.handleStaleConversationError(
1110+
error,
1111+
instance,
1112+
conversationId,
1113+
messageBody,
1114+
messageBodyForRetry,
1115+
'sendData',
1116+
(newConvId) => doSendData(newConvId),
1117+
);
11171118
}
11181119
}
11191120

0 commit comments

Comments
 (0)