【发布时间】:2019-05-19 09:07:18
【问题描述】:
我正在尝试在 Lambda 函数中运行的 alexa 技能中记录错误,但无论我尝试什么,错误都会以某种方式通过我的 try/catch 块而不被记录。
这是我的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();
}
顶级try/catch 应捕获require('./handlers') 期间引发的任何错误。过去我观察到这种工作在我的处理程序中捕获语法错误。
我还将每个处理程序的handle 函数包装在try/catch 中(请参阅wrappedHandlers)。我的错误处理程序还会记录它看到的任何错误:
// 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();
},
};
尽管如此,Alexa 模拟器仍在输出 [Error]: An unexpected error occurred.,但 cloudwatch 日志不包含任何错误或失败的请求。这怎么可能?
【问题讨论】:
-
speachMessage->speechMessage? -
这是一个错字,但始终是一致的,所以我认为它不会导致问题。尽管在错误处理程序中引发错误会导致此问题是有道理的,但我将对此进行更多测试。
标签: javascript aws-lambda alexa-skills-kit