Skip to content

Commit

Permalink
Adding error logging
Browse files Browse the repository at this point in the history
  • Loading branch information
fwang committed Apr 8, 2020
1 parent 777bad3 commit 6b0e70e
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
42 changes: 42 additions & 0 deletions libs/debug-lib.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import AWS from "aws-sdk";
import util from "util";

// Log AWS SDK calls
AWS.config.logger = { log: debug };

let logs;
let timeoutTimer;

export function init(event, context) {
logs = [];

// Log API event
debug("API event", {
body: event.body,
pathParameters: event.pathParameters,
queryStringParameters: event.queryStringParameters,
});

// Start timeout timer
timeoutTimer = setTimeout(() => {
timeoutTimer && flush(new Error("Lambda will timeout in 100 ms"));
}, context.getRemainingTimeInMillis() - 100);
}

export function end() {
// Clear timeout timer
clearTimeout(timeoutTimer);
timeoutTimer = null;
}

export function flush(e) {
logs.forEach(({ date, string }) => console.debug(date, string));
console.error(e);
}

export default function debug() {
logs.push({
date: new Date(),
string: util.format.apply(null, arguments),
});
}
10 changes: 9 additions & 1 deletion libs/handler-lib.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import * as debug from "./debug-lib";

export default function handler(lambda) {
return function (event, context) {
return Promise.resolve()
// Start debugger
.then(() => debug.init(event, context))
// Run the Lambda
.then(() => lambda(event, context))
// On success
.then((responseBody) => [200, responseBody])
// On failure
.catch((e) => {
// Print debug messages
debug.flush(e);
return [500, { error: e.message }];
})
// Return HTTP response
Expand All @@ -17,6 +23,8 @@ export default function handler(lambda) {
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify(body),
}));
}))
// Cleanup debugger
.finally(debug.end);
};
}

0 comments on commit 6b0e70e

Please sign in to comment.