diff --git a/app/services/facebook/send_on_facebook_service.rb b/app/services/facebook/send_on_facebook_service.rb index d85820b48..bf78edb16 100644 --- a/app/services/facebook/send_on_facebook_service.rb +++ b/app/services/facebook/send_on_facebook_service.rb @@ -9,9 +9,8 @@ class Facebook::SendOnFacebookService < Base::SendOnChannelService send_message_to_facebook fb_text_message_params if message.content.present? send_message_to_facebook fb_attachment_message_params if message.attachments.present? rescue Facebook::Messenger::FacebookError => e - ChatwootExceptionTracker.new(e, account: message.account, user: message.sender).capture_exception # TODO : handle specific errors or else page will get disconnected - # channel.authorization_error! + handle_facebook_error(e) end def send_message_to_facebook(delivery_params) @@ -67,4 +66,13 @@ class Facebook::SendOnFacebookService < Base::SendOnChannelService def last_incoming_message conversation.messages.incoming.last end + + def handle_facebook_error(exception) + # Refer: https://github.com/jgorset/facebook-messenger/blob/64fe1f5cef4c1e3fca295b205037f64dfebdbcab/lib/facebook/messenger/error.rb + if exception.to_s.include?('The session has been invalidated') || exception.to_s.include?('Error validating access token') + channel.authorization_error! + else + ChatwootExceptionTracker.new(exception, account: message.account, user: message.sender).capture_exception + end + end end diff --git a/spec/services/facebook/send_on_facebook_service_spec.rb b/spec/services/facebook/send_on_facebook_service_spec.rb index 674700c4d..dc938550b 100644 --- a/spec/services/facebook/send_on_facebook_service_spec.rb +++ b/spec/services/facebook/send_on_facebook_service_spec.rb @@ -52,6 +52,14 @@ describe Facebook::SendOnFacebookService do expect(bot).to have_received(:deliver) end + it 'raise and exception to validate access token' do + message = create(:message, message_type: 'outgoing', inbox: facebook_inbox, account: account, conversation: conversation) + allow(bot).to receive(:deliver).and_raise(Facebook::Messenger::FacebookError.new('message' => 'Error validating access token')) + ::Facebook::SendOnFacebookService.new(message: message).perform + + expect(facebook_channel.authorization_error_count).to eq(1) + end + it 'if message with attachment is sent from chatwoot and is outgoing' do message = build(:message, message_type: 'outgoing', inbox: facebook_inbox, account: account, conversation: conversation) attachment = message.attachments.new(account_id: message.account_id, file_type: :image)