Skip to content

Instantly share code, notes, and snippets.

import middy from '@middy/core';
// Business logic
const businessLogic = async (event) => {
...
return myResponse;
};
// Configuration
export const myHandler = middy(businessLogic).onError(handleError);
const handler = async () => ({
statusCode: 200,
body: JSON.stringify({ fruits: ['What a great tomato'] }),
headers: { 'Content-Type': 'application/json' },
});
const formatErrorForApiGateway = ({ error }) => {
const { statusCode, key, message } =
error instanceof CustomError
? error
: new InternalServerError({ message: error.message });
throw `[${statusCode}] [${key}] ${message}`;
};
const parseStatusCode = (originalStatusCode) => {
switch (true) {
case defaultStatusCodes.has(originalStatusCode):
return originalStatusCode;
case originalStatusCode < 500:
return 400;
default:
return 500;
}
};
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}`);
}
...
}
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();
}
const formatErrorForApiGateway = ({ parsers } = { parsers: [] }) =>
({ error }) => {
const { statusCode, key, message } = parseError(error, parsers);
throw `[${statusCode}] [${key}] ${message}`;
};
...
const handler = middy(businessLogic)
.onError(formatErrorForApiGateway({ parsers: [parseAxiosError] });
functions:
myLambda:
...
integration: lambda
response:
statusCodes:
200:
pattern: '' # Default response method
400:
pattern: '.*"statusCode":400.*'
const formatErrorForApiGateway = ({ parsers } = { parsers: [] }) =>
({ error }) => {
const { statusCode, key, message } = parseError(error, parsers);
throw JSON.stringify({ statusCode, key, message });
};
functions:
myLambda:
...
integration: lambda
response: ${file(./response.yml)}