I'm trying to log errors in an alexa skill that runs in a Lambda function, but no matter what I try, errors somehow get through my try/catch
blocks without being logged.
This is my index.js
:
const Alexa = require('ask-sdk-core');
try {
const handlers = require('./handlers');
const wrappedHandlers = handlers.map(handler => ({
...handler,
async handle(handlerInput) {
try {
console.log(`Running handler ${handler.name}`, JSON.stringify(handlerInput, null, 2));
const response = await handler.handle(handlerInput);
console.log(`Successfully ran handler ${handler.name}`, JSON.stringify(response, null, 2));
return response;
} catch(error) {
console.log(`Failed to run handler ${handler.name}`, error.stack);
throw error;
}
},
}));
exports.handler = Alexa.SkillBuilders
.custom()
.addRequestHandlers(...wrappedHandlers)
.addErrorHandlers(require('./handlers/error'))
.lambda();
} catch(error) {
console.log('Fatal initialization error', error);
exports.handler = Alexa.SkillBuilders
.custom()
.addRequestHandlers({
canHandle() { return true; },
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(`Initialization error`, error.stack);
},
})
.lambda();
}
The top-level try/catch
should catch any errors thrown during require('./handlers')
. I've observed this working in the past catching syntax errors in my handlers.
I'm also wrapping every handler's handle
function in a try/catch
(see wrappedHandlers
). My error handler also logs any errors it sees:
// handlers/error.js
module.exports = {
canHandle() { return true; },
handle(handlerInput, error) {
console.log(`Error handled: ${error.stack}`);
// During tests, include the error in the response
if(process.env['NODE_ENV'] === 'test') {
const { attributesManager } = handlerInput;
const sessionAttributes = attributesManager.getSessionAttributes();
sessionAttributes.error = error;
attributesManager.setSessionAttributes(sessionAttributes);
}
const message = error && error.speachMessage || `Sorry, I can't understand the command. Please say again. ${error.stack}`;
return handlerInput.responseBuilder
.speak(message)
.reprompt(message)
.getResponse();
},
};
Despite all of this, the Alexa simulator is spitting out [Error]: An unexpected error occurred.
, but the cloudwatch logs don't contain any errors or failed requests. How is this possible?