From 163b721271ed69ddef4436b3f60605734f264252 Mon Sep 17 00:00:00 2001 From: pac7 <47831526-pac7@users.noreply.replit.com> Date: Wed, 8 Oct 2025 12:07:42 +0000 Subject: [PATCH] Improve email sending by adding error handling and fixing security Add try-catch blocks to Supabase functions for robust error handling during email sending and response processing. Replit-Commit-Author: Agent Replit-Commit-Session-Id: a46bc7a0-bbf8-43ab-97c0-a58c66c2e365 Replit-Commit-Checkpoint-Type: intermediate_checkpoint --- .../send-escalation-notification/index.ts | 49 +++++++++++++------ 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/supabase/functions/send-escalation-notification/index.ts b/supabase/functions/send-escalation-notification/index.ts index 33bebbb3..beb07332 100644 --- a/supabase/functions/send-escalation-notification/index.ts +++ b/supabase/functions/send-escalation-notification/index.ts @@ -162,28 +162,45 @@ serve(async (req) => { throw new Error('Email configuration is incomplete. Please check environment variables.'); } - const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', { - method: 'POST', - headers: { - 'Authorization': 'Basic ' + btoa(forwardEmailApiKey + ':'), - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - from: fromEmail, - to: adminEmail, - subject: emailSubject, - html: emailHtml, - text: emailText, - }), - }); + let emailResponse; + try { + emailResponse = await fetch('https://api.forwardemail.net/v1/emails', { + method: 'POST', + headers: { + 'Authorization': 'Basic ' + btoa(forwardEmailApiKey + ':'), + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + from: fromEmail, + to: adminEmail, + subject: emailSubject, + html: emailHtml, + text: emailText, + }), + }); + } catch (fetchError) { + console.error('Network error sending email:', fetchError); + throw new Error('Network error: Unable to reach email service'); + } if (!emailResponse.ok) { - const errorText = await emailResponse.text(); + let errorText; + try { + errorText = await emailResponse.text(); + } catch (parseError) { + errorText = 'Unable to parse error response'; + } console.error('ForwardEmail API error:', errorText); throw new Error(`Failed to send email: ${emailResponse.status} - ${errorText}`); } - const emailResult = await emailResponse.json(); + let emailResult; + try { + emailResult = await emailResponse.json(); + } catch (parseError) { + console.error('Failed to parse email API response:', parseError); + throw new Error('Invalid response from email service'); + } console.log('Email sent successfully:', emailResult); // Update submission with notification status