Skip to content

Instantly share code, notes, and snippets.

View fig-9.js
const formatErrorForApiGateway = ({ parsers } = { parsers: [] }) =>
({ error }) => {
const { statusCode, key, message } = parseError(error, parsers);
throw `[${statusCode}] [${key}] ${message}`;
};
...
const handler = middy(businessLogic)
.onError(formatErrorForApiGateway({ parsers: [parseAxiosError] });
View fig-12.js
functions:
myLambda:
...
integration: lambda
response: ${file(./response.yml)}
View fig-11.js
const formatErrorForApiGateway = ({ parsers } = { parsers: [] }) =>
({ error }) => {
const { statusCode, key, message } = parseError(error, parsers);
throw JSON.stringify({ statusCode, key, message });
};
View fig-10.yml
functions:
myLambda:
...
integration: lambda
response:
statusCodes:
200:
pattern: '' # Default response method
400:
pattern: '.*"statusCode":400.*'
View fig-8.js
const parseError = (originalError, parsers) => {
let error = originalError;
while (!(error instanceof CustomError) && parsers.length) {
const { detect, parse } = parsers[0];
if (detect(error)) {
error = parse(error);
}
parsers.shift();
}
View fig-7.js
const parseStatusCode = (originalStatusCode) => {
switch (true) {
case defaultStatusCodes.has(originalStatusCode):
return originalStatusCode;
case originalStatusCode < 500:
return 400;
default:
return 500;
}
};
View fig-6.js
const defaultStatusCodes = new Set([400, 401, 403, 404, 422, 500, 502, 504]);
class CustomError extends Error {
constructor(statusCode: number, { key, message, payload }) {
super(message);
if (!defaultStatusCodes.has(statusCode)) {
throw new Error(`No integration response associated with statusCode ${statusCode}`);
}
...
}
View fig-5.js
const formatErrorForApiGateway = ({ error }) => {
const { statusCode, key, message } =
error instanceof CustomError
? error
: new InternalServerError({ message: error.message });
throw `[${statusCode}] [${key}] ${message}`;
};
View fig-4.js
const createProxyHttpResponse = ({ statusCode, key, message }) => ({
statusCode,
body: JSON.stringify({ key, message }),
headers: { 'Content-Type': 'application/json' },
});
const formatErrorForApiGateway = async ({ error, callback }) =>
callback(
null,
createProxyHttpResponse(
View fig-3.js
const handler = async () => ({
statusCode: 200,
body: JSON.stringify({ fruits: ['What a great tomato'] }),
headers: { 'Content-Type': 'application/json' },
});