diff --git a/src/server/common/connectors/notify/notify.js b/src/server/common/connectors/notify/notify.js index cf4d1744..abdfe166 100644 --- a/src/server/common/connectors/notify/notify.js +++ b/src/server/common/connectors/notify/notify.js @@ -10,14 +10,14 @@ const notifyConfig = config.get('notify') /** * @param {NotifyContent} data */ -export function sendNotification(data) { +export async function sendNotification(data) { const body = JSON.stringify({ template_id: notifyConfig.templateId, email_address: notifyConfig.caseDeliveryEmailAddress, personalisation: data }) - return proxyFetch( + const response = await proxyFetch( 'https://api.notifications.service.gov.uk/v2/notifications/email', { method: 'POST', @@ -26,10 +26,14 @@ export function sendNotification(data) { Authorization: 'Bearer ' + createToken(notifyConfig.apiKey) } } - ).then((response) => { - if (!response.ok) { - throw new Error() - } - return response - }) + ) + + if (!response.ok) { + const responseBody = await response.json() + const errors = responseBody.errors.map((error) => error.message) + throw new Error( + `HTTP failure from GOV.uk notify: status ${response.status} with the following errors: ${errors.join(', ')}` + ) + } + return response } diff --git a/src/server/common/connectors/notify/notify.test.js b/src/server/common/connectors/notify/notify.test.js index 1ff52a98..5598f367 100644 --- a/src/server/common/connectors/notify/notify.test.js +++ b/src/server/common/connectors/notify/notify.test.js @@ -42,9 +42,30 @@ describe('sendNotification', () => { }) it('should throw an error if the response is not ok', async () => { - const mockResponse = { ok: false } + const mockResponse = { + ok: false, + status: 400, + + // eslint-disable-next-line @typescript-eslint/require-await + json: async () => ({ + status_code: 400, + errors: [ + { + error: 'BadRequestError', + message: "Can't send to this recipient using a team-only API key" + }, + { + error: 'BadRequestError', + message: + "Can't send to this recipient when service is in trial mode" + } + ] + }) + } mockProxyFetch.mockImplementation(() => Promise.resolve(mockResponse)) - await expect(sendNotification(testData)).rejects.toThrow() + await expect(sendNotification(testData)).rejects.toThrow( + "HTTP failure from GOV.uk notify: status 400 with the following errors: Can't send to this recipient using a team-only API key, Can't send to this recipient when service is in trial mode" + ) }) })