Skip to content

Commit 6b0e70e

Browse files
committed
Adding error logging
1 parent 777bad3 commit 6b0e70e

2 files changed

Lines changed: 51 additions & 1 deletion

File tree

libs/debug-lib.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import AWS from "aws-sdk";
2+
import util from "util";
3+
4+
// Log AWS SDK calls
5+
AWS.config.logger = { log: debug };
6+
7+
let logs;
8+
let timeoutTimer;
9+
10+
export function init(event, context) {
11+
logs = [];
12+
13+
// Log API event
14+
debug("API event", {
15+
body: event.body,
16+
pathParameters: event.pathParameters,
17+
queryStringParameters: event.queryStringParameters,
18+
});
19+
20+
// Start timeout timer
21+
timeoutTimer = setTimeout(() => {
22+
timeoutTimer && flush(new Error("Lambda will timeout in 100 ms"));
23+
}, context.getRemainingTimeInMillis() - 100);
24+
}
25+
26+
export function end() {
27+
// Clear timeout timer
28+
clearTimeout(timeoutTimer);
29+
timeoutTimer = null;
30+
}
31+
32+
export function flush(e) {
33+
logs.forEach(({ date, string }) => console.debug(date, string));
34+
console.error(e);
35+
}
36+
37+
export default function debug() {
38+
logs.push({
39+
date: new Date(),
40+
string: util.format.apply(null, arguments),
41+
});
42+
}

libs/handler-lib.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
1+
import * as debug from "./debug-lib";
2+
13
export default function handler(lambda) {
24
return function (event, context) {
35
return Promise.resolve()
6+
// Start debugger
7+
.then(() => debug.init(event, context))
48
// Run the Lambda
59
.then(() => lambda(event, context))
610
// On success
711
.then((responseBody) => [200, responseBody])
812
// On failure
913
.catch((e) => {
14+
// Print debug messages
15+
debug.flush(e);
1016
return [500, { error: e.message }];
1117
})
1218
// Return HTTP response
@@ -17,6 +23,8 @@ export default function handler(lambda) {
1723
"Access-Control-Allow-Credentials": true,
1824
},
1925
body: JSON.stringify(body),
20-
}));
26+
}))
27+
// Cleanup debugger
28+
.finally(debug.end);
2129
};
2230
}

0 commit comments

Comments
 (0)