feat(graphql): improve sendgrid errors

This commit is contained in:
Sam Tolmay 2020-11-17 12:50:35 +02:00
parent e8a36c443d
commit 72fac1d81e
2 changed files with 51 additions and 19 deletions

View File

@ -57,16 +57,11 @@ async function sendGridMailSend({ request, connection, context }) {
};
try {
await sendgrid.send(msg);
} catch (err) {
throw new context.RequestError(
`${
(err.response &&
err.response.body.errors.map(
(error) => `field: '${error.field}', message: '${error.message}'`
)) ||
JSON.stringify(err)
}`
);
} catch (error) {
if (error.response) {
throw new context.RequestError(JSON.stringify(error.response.body));
}
throw new context.RequestError(error.message);
}
return { response: 'Mail sent successfully' };
}

View File

@ -22,15 +22,22 @@ const { resolver, schema } = SendGridMailSend;
const context = { ConfigurationError, RequestError };
jest.mock('@sendgrid/mail', () => ({
jest.mock('@sendgrid/mail', () => {
return {
setApiKey: jest.fn(),
send: (msg) => {
if (msg.templateId === 'template error') {
throw new Error({ response: { body: 'Error test' } });
if (msg.to === 'response_error') {
const error = new Error('Test error.');
error.response = { body: ['Test error 1.', 'Test error 2.'] };
throw error;
}
if (msg.to === 'generic_error') {
throw new Error('Test error.');
}
return Promise.resolve(msg);
},
}));
};
});
afterEach(() => {
jest.resetAllMocks();
@ -159,3 +166,33 @@ test('Error request with dynamicTemplateData is not an object', async () => {
'SendGridMailSend request properties should be an object or a array describing emails to send.'
);
});
test('request throws an error', async () => {
const request = {
to: 'generic_error',
subject: 'A',
text: 'B',
};
const connection = {
apiKey: 'X',
from: { name: 'a@b.om', email: 'a.cc@mm.co' },
};
await expect(() => resolver({ request, connection, context })).rejects.toThrow(RequestError);
await expect(() => resolver({ request, connection, context })).rejects.toThrow('Test error');
});
test('request throws an error with response body', async () => {
const request = {
to: 'response_error',
subject: 'A',
text: 'B',
};
const connection = {
apiKey: 'X',
from: { name: 'a@b.om', email: 'a.cc@mm.co' },
};
await expect(() => resolver({ request, connection, context })).rejects.toThrow(RequestError);
await expect(() => resolver({ request, connection, context })).rejects.toThrow(
'["Test error 1.","Test error 2."]'
);
});