improve email error handling
This commit is contained in:
1 parent
41c7cfbdaa
commit
4a66cf6e11
9 files changed
+183
-33
No files matched your search
@@ -35,11 +35,18 @@ class NotificationController implements INotificationController {
|
||||
|
||||
testNotification = catchAsync(async (req: Request, res: Response) => {
|
||||
const notification = testNotificationBodyValidation.parse(req.body);
|
||||
const success = await this.notificationsService.sendTestNotification(notification);
|
||||
let success = false;
|
||||
let reason: string | undefined;
|
||||
try {
|
||||
success = await this.notificationsService.sendTestNotification(notification);
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof AppError)) throw error;
|
||||
reason = error.message;
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
success,
|
||||
msg: success ? "Notification sent successfully" : "Notification could not be sent — check the destination details.",
|
||||
msg: success ? "Notification sent successfully" : (reason ?? "Notification could not be sent — check the destination details."),
|
||||
details: { service: SERVICE_NAME },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,8 @@ import { IProxiesService } from "@/domain/proxies/proxy.service.js";
|
||||
import { IEgressStateService } from "@/domain/egress/egress-state.service.js";
|
||||
import { Settings } from "@/domain/app-settings/app-settings.type.js";
|
||||
|
||||
const SERVICE_NAME = "SettingsController";
|
||||
|
||||
export interface ISettingsController {
|
||||
getAppSettings: RequestHandler;
|
||||
updateAppSettings: RequestHandler;
|
||||
@@ -119,7 +121,7 @@ class SettingsController implements ISettingsController {
|
||||
|
||||
const html = await this.emailService.buildEmail("testEmailTemplate", context);
|
||||
if (!html) {
|
||||
throw new AppError({ message: "Failed to build email template.", status: 500 });
|
||||
throw new AppError({ message: "Failed to build email template.", status: 500, service: SERVICE_NAME, method: "sendTestEmail" });
|
||||
}
|
||||
let messageId: string;
|
||||
try {
|
||||
@@ -142,8 +144,11 @@ class SettingsController implements ISettingsController {
|
||||
// Surface the underlying SMTP failure: diagnosing the settings is the whole
|
||||
// point of the test email endpoint.
|
||||
throw new AppError({
|
||||
message: error instanceof Error ? `Failed to send test email. ${error.message}` : "Failed to send test email.",
|
||||
status: 500,
|
||||
message: error instanceof AppError ? error.message : "Failed to send test email.",
|
||||
status: error instanceof AppError ? error.status : 500,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestEmail",
|
||||
details: error instanceof AppError ? error.details : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -148,7 +148,17 @@ export class NotificationsService implements INotificationsService {
|
||||
|
||||
testAllNotifications = async (notificationIds: string[]) => {
|
||||
const notifications = await this.notificationsRepository.findNotificationsByIds(notificationIds);
|
||||
const tasks = notifications.map((notification) => this.sendTestNotification(notification));
|
||||
const tasks = notifications.map((notification) =>
|
||||
this.sendTestNotification(notification).catch((error: unknown) => {
|
||||
this.logger.warn({
|
||||
message: `Test notification failed: ${error instanceof Error ? error.message : "Unknown error"}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "testAllNotifications",
|
||||
details: { notificationId: notification.id, type: notification.type },
|
||||
});
|
||||
return false;
|
||||
})
|
||||
);
|
||||
const outcomes = await Promise.all(tasks);
|
||||
const succeeded = outcomes.filter(Boolean).length;
|
||||
const failed = outcomes.length - succeeded;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const SERVICE_NAME = "EmailProvider";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { buildTestEmail } from "@/domain/notifications/providers/utils.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import type { ILogger } from "@/utils/logger.js";
|
||||
@@ -40,11 +41,13 @@ export class EmailProvider extends NotificationProvider {
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
message: "Email test alert failed",
|
||||
message: `Email test alert failed: ${error instanceof Error ? error.message : "Unknown error"}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
details: error instanceof AppError ? error.details : undefined,
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
if (error instanceof AppError) throw error;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -73,9 +76,10 @@ export class EmailProvider extends NotificationProvider {
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
message: "Email notification failed",
|
||||
message: `Email notification failed: ${error instanceof Error ? error.message : "Unknown error"}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
details: error instanceof AppError ? error.details : undefined,
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
return false;
|
||||
|
||||
@@ -12,6 +12,23 @@ const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const SERVICE_NAME = "EmailService";
|
||||
|
||||
const SMTP_FAILURE_REASONS: Record<string, string> = {
|
||||
EAUTH: "rejected the login. Check the user name and password",
|
||||
ENOAUTH: "requires a login. Set the user name and password",
|
||||
EDNS: "could not be resolved. Check the host name",
|
||||
ECONNECTION: "refused the connection. Check the host and port",
|
||||
ESOCKET: "refused the connection. Check the host and port",
|
||||
ETIMEDOUT: "did not respond. Check the port and the secure setting",
|
||||
ETLS: "failed the TLS handshake. Check the secure and TLS settings",
|
||||
EPROTOCOL: "sent an invalid response. Check the port and the secure setting",
|
||||
};
|
||||
|
||||
const describeSmtpFailure = (error: unknown, host: string, port: number): string => {
|
||||
const code = typeof error === "object" && error !== null && "code" in error ? String((error as { code: unknown }).code) : undefined;
|
||||
const reason = (code !== undefined && SMTP_FAILURE_REASONS[code]) || "failed verification";
|
||||
return `SMTP host ${host}:${port} ${reason}.`;
|
||||
};
|
||||
type MjmlFn = typeof mjml2html;
|
||||
type FileSystem = typeof fs;
|
||||
type PathModule = typeof path;
|
||||
@@ -123,6 +140,15 @@ export class EmailService implements IEmailService {
|
||||
systemEmailRejectUnauthorized,
|
||||
} = config;
|
||||
|
||||
if (!systemEmailHost) {
|
||||
throw new AppError({
|
||||
message: "Email is not configured. Set the system email host in settings.",
|
||||
status: 400,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendEmail",
|
||||
});
|
||||
}
|
||||
|
||||
const emailConfig = {
|
||||
host: systemEmailHost,
|
||||
port: Number(systemEmailPort),
|
||||
@@ -146,17 +172,20 @@ export class EmailService implements IEmailService {
|
||||
try {
|
||||
await this.transporter.verify();
|
||||
} catch (error: unknown) {
|
||||
const cause = error instanceof Error ? error.message : "Unknown error";
|
||||
this.logger.warn({
|
||||
message: "Email transporter verification failed",
|
||||
message: `Email transporter verification failed: ${cause}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "verifyTransporter",
|
||||
details: { host: systemEmailHost, port: emailConfig.port },
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw new AppError({
|
||||
message: "Email transporter verification failed",
|
||||
message: describeSmtpFailure(error, systemEmailHost, emailConfig.port),
|
||||
status: 502,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendEmail",
|
||||
details: { cause: error instanceof Error ? error.message : "Unknown error" },
|
||||
details: { cause },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -180,6 +209,7 @@ export class EmailService implements IEmailService {
|
||||
});
|
||||
throw new AppError({
|
||||
message: "Failed to send email",
|
||||
status: 502,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendEmail",
|
||||
details: { cause: error instanceof Error ? error.message : "Unknown error" },
|
||||
|
||||
+12
-15
@@ -60,21 +60,18 @@ class Logger implements ILogger {
|
||||
if (formattedDetails) msg += ` (details: ${formattedDetails})`;
|
||||
|
||||
if (typeof stack === "string") {
|
||||
const stackTrace = stack
|
||||
.split("\n")
|
||||
.slice(1) // Remove first line (error message)
|
||||
.map((line: string) => {
|
||||
const match = line.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
|
||||
if (match) {
|
||||
return {
|
||||
function: match[1],
|
||||
file: match[2],
|
||||
line: parseInt(match[3] ?? "0", 10),
|
||||
column: parseInt(match[4] ?? "0", 10),
|
||||
};
|
||||
}
|
||||
return line.trim();
|
||||
});
|
||||
const stackTrace = stack.split("\n").map((line: string) => {
|
||||
const match = line.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
|
||||
if (match) {
|
||||
return {
|
||||
function: match[1],
|
||||
file: match[2],
|
||||
line: parseInt(match[3] ?? "0", 10),
|
||||
column: parseInt(match[4] ?? "0", 10),
|
||||
};
|
||||
}
|
||||
return line.trim();
|
||||
});
|
||||
msg += ` (stack: ${JSON.stringify(stackTrace, null, 2)})`;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user