improve email error handling

This commit is contained in:
Alex Holliday committed 2026-09-23 12:13:27 -07:00
1 parent 41c7cfbdaa
commit 4a66cf6e11
9 files changed
+183 -33

No files matched your search

@@ -4,6 +4,7 @@ import { createMockLogger } from "../../../helpers/createMockLogger.ts";
import { makeNotification, makeMessage } from "../../../helpers/notificationMessage.ts";
import { testNotificationProviderContract } from "../../../helpers/notificationProviderContract.ts";
import type { IEmailService } from "../../../../src/service/emailService.ts";
import { AppError } from "../../../../src/utils/AppError.ts";
// ── Helpers ──────────────────────────────────────────────────────────────────
@@ -50,11 +51,29 @@ describe("EmailProvider", () => {
expect(logger.warn).toHaveBeenCalledWith(expect.objectContaining({ message: "Failed to build test email content" }));
});
it("returns false when sendEmail rejects", async () => {
it("returns false and logs the cause when sendEmail rejects with a plain error", async () => {
const { provider, emailService, logger } = createProvider();
(emailService.sendEmail as jest.Mock).mockRejectedValue(new Error("SMTP auth failed"));
expect(await provider.sendTestAlert(makeNotification())).toBe(false);
expect(logger.warn).toHaveBeenCalledWith(expect.objectContaining({ message: "Email test alert failed" }));
expect(logger.warn).toHaveBeenCalledWith(expect.objectContaining({ message: "Email test alert failed: SMTP auth failed" }));
});
it("rethrows an AppError from sendEmail so the caller can report the reason", async () => {
const { provider, emailService, logger } = createProvider();
const error = new AppError({
message: "Email is not configured. Set the system email host in settings.",
status: 400,
details: { cause: "no host" },
});
(emailService.sendEmail as jest.Mock).mockRejectedValue(error);
await expect(provider.sendTestAlert(makeNotification())).rejects.toBe(error);
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({
message: "Email test alert failed: Email is not configured. Set the system email host in settings.",
details: { cause: "no host" },
})
);
});
});
@@ -84,11 +103,29 @@ describe("EmailProvider", () => {
// NotificationsService fans providers out through Promise.all, so a failed email must
// resolve to false rather than reject and take the other channels down with it.
it("returns false when sendEmail rejects", async () => {
it("returns false and logs the cause when sendEmail rejects", async () => {
const { provider, emailService, logger } = createProvider();
(emailService.sendEmail as jest.Mock).mockRejectedValue(new Error("SMTP auth failed"));
expect(await provider.sendMessage(makeNotification() as any, makeMessage())).toBe(false);
expect(logger.warn).toHaveBeenCalledWith(expect.objectContaining({ message: "Email notification failed" }));
expect(logger.warn).toHaveBeenCalledWith(expect.objectContaining({ message: "Email notification failed: SMTP auth failed" }));
});
it("returns false rather than throwing when sendEmail rejects with an AppError", async () => {
const { provider, emailService, logger } = createProvider();
(emailService.sendEmail as jest.Mock).mockRejectedValue(
new AppError({
message: "SMTP verification failed for smtp.example.com:587: 535 Username and Password not accepted",
status: 502,
details: { cause: "ECONNREFUSED" },
})
);
expect(await provider.sendMessage(makeNotification() as any, makeMessage())).toBe(false);
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({
message: "Email notification failed: SMTP verification failed for smtp.example.com:587: 535 Username and Password not accepted",
details: { cause: "ECONNREFUSED" },
})
);
});
it("builds correct subject for monitor_down", async () => {
+46 -3
View File
@@ -335,17 +335,60 @@ describe("EmailService", () => {
const { service, logger } = createService({ nodemailer });
await expect(service.sendEmail("to@example.com", "Subject", "<p>body</p>", makeTransportConfig())).rejects.toThrow(
"Email transporter verification failed"
"SMTP host smtp.example.com:587 failed verification."
);
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({
message: "Email transporter verification failed",
message: "Email transporter verification failed: SMTP auth failed",
service: "EmailService",
method: "verifyTransporter",
details: { host: "smtp.example.com", port: 587 },
})
);
});
it.each([
["EAUTH", "SMTP host smtp.example.com:587 rejected the login. Check the user name and password."],
["ETIMEDOUT", "SMTP host smtp.example.com:587 did not respond. Check the port and the secure setting."],
["EDNS", "SMTP host smtp.example.com:587 could not be resolved. Check the host name."],
["ECONNECTION", "SMTP host smtp.example.com:587 refused the connection. Check the host and port."],
["ETLS", "SMTP host smtp.example.com:587 failed the TLS handshake. Check the secure and TLS settings."],
])("describes a %s verification failure without the server's reply text", async (code, expected) => {
const transporter = createMockTransporter();
(transporter.verify as jest.Mock).mockRejectedValue(Object.assign(new Error("535-5.7.8 Username and Password not accepted"), { code }));
const nodemailer = createMockNodemailer(transporter);
const { service } = createService({ nodemailer });
await expect(service.sendEmail("to@example.com", "Subject", "<p>body</p>", makeTransportConfig())).rejects.toMatchObject({
message: expected,
status: 502,
details: { cause: "535-5.7.8 Username and Password not accepted" },
});
});
it("throws a 400 without building a transport when the host is not configured", async () => {
const nodemailer = createMockNodemailer();
const { service } = createService({ nodemailer });
await expect(
service.sendEmail("to@example.com", "Subject", "<p>body</p>", makeTransportConfig({ systemEmailHost: undefined }))
).rejects.toMatchObject({
status: 400,
message: "Email is not configured. Set the system email host in settings.",
});
expect(nodemailer.createTransport).not.toHaveBeenCalled();
});
it("treats an empty host as not configured", async () => {
const { service } = createService();
await expect(service.sendEmail("to@example.com", "Subject", "<p>body</p>", makeTransportConfig({ systemEmailHost: "" }))).rejects.toMatchObject(
{
status: 400,
}
);
});
it("reports the underlying cause when verification fails", async () => {
const transporter = createMockTransporter();
(transporter.verify as jest.Mock).mockRejectedValue(new Error("SMTP auth failed"));
@@ -353,7 +396,7 @@ describe("EmailService", () => {
const { service } = createService({ nodemailer });
await expect(service.sendEmail("to@example.com", "Subject", "<p>body</p>", makeTransportConfig())).rejects.toMatchObject({
status: 500,
status: 502,
details: { cause: "SMTP auth failed" },
});
});
@@ -311,6 +311,23 @@ describe("NotificationsService", () => {
const result = await service.testAllNotifications(["notif-1"]);
expect(result).toBe(false);
});
it("counts a provider that throws as a failed test and still tests the others", async () => {
const { service, notificationsRepository, emailProvider, slackProvider, logger } = createService();
emailProvider.sendTestAlert.mockRejectedValue(new Error("Email is not configured. Set the system email host in settings."));
(notificationsRepository.findNotificationsByIds as jest.Mock).mockResolvedValue([
makeNotification({ type: "email" }),
makeNotification({ type: "slack" }),
]);
const result = await service.testAllNotifications(["notif-1", "notif-2"]);
expect(result).toBe(false);
expect(slackProvider.sendTestAlert).toHaveBeenCalled();
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ message: "Test notification failed: Email is not configured. Set the system email host in settings." })
);
});
});
// ── CRUD operations ──────────────────────────────────────────────────────