如何在Alexa ASK SDK V2中使用addErrorHandlers

时间:2019-02-05 01:16:55

标签: node.js alexa alexa-skills-kit alexa-skill

我正在尝试将我的技能从V1升级到ASK SDK V2。我在addErrorHandlers上使用StandardSkillBuilder函数时遇到麻烦。当我故意抛出错误时,永远不会调用我的自定义错误处理程序。我不确定如何使用它。

index.ts

import { SkillBuilders } from 'ask-sdk';
import { LambdaHandler } from 'ask-sdk-core/dist/skill/factory/BaseSkillFactory';

// import intents
import LaunchIntent from './alexa-intents/launch.intent';
import CustomErrorHandler from './alexa-intents/custom-error-handler';

function buildAlexaLambdaHandler(): LambdaHandler {
    return SkillBuilders.standard()
        .addRequestHandlers(
            new LaunchIntent()
        )
        .addErrorHandlers(new CustomErrorHandler())
        .lambda();
}

export const handler = buildAlexaLambdaHandler();

launch.intent.ts (引发测试错误)

import { HandlerInput, RequestHandler } from 'ask-sdk';
import { Response } from 'ask-sdk-model'

export default class LaunchIntent implements RequestHandler {
    canHandle(handlerInput: HandlerInput): boolean {
        const request = handlerInput.requestEnvelope.request;
        return request.type === 'LaunchRequest';
    }

    handle(handlerInput: HandlerInput): Response {
        const responseBuilder = handlerInput.responseBuilder;
        const deviceId = handlerInput.requestEnvelope.context.System.device.deviceId;
        if (deviceId) {
            console.log('throwing error');
            throw new Error('test error');
        }
        return responseBuilder
            .speak('welcome')
            .getResponse();
    }
}

custom-error-handler.ts (试图捕获测试错误)

import { HandlerInput, ErrorHandler } from 'ask-sdk';
import { Response } from 'ask-sdk-model';

export default class CustomErrorHandler implements ErrorHandler {

    canHandle(handlerInput: HandlerInput): boolean {
        return true;
    }

    handle(handlerInput: HandlerInput, error: Error): Response {
        const request = handlerInput.requestEnvelope.request;
        const deviceId = handlerInput.context.System.device.deviceId;
        console.dir(error);

        return handlerInput.responseBuilder
            .speak('there was an error')
            .getResponse();
    }
}

我正在使用bespoken-tools LambdaServer在本地进行技能训练:

import * as bst from 'bespoken-tools';

const server = new bst.LambdaServer('./src/index', 10000, true);
server.start(() => console.log('[init.dev]: server started and listening on port 10000!'));

在我的控制台日志中,我从启动意图处理程序“ throwing error”中看到了控制台消息,但是随后我再也没有看到调用过CustomErrorHandler或其中的任何控制台日志。在Alexa开发人员控制台模拟器中,我得到“请求的技能的响应存在问题”,因为CustomerErrorHandler从未添加任何响应。

1 个答案:

答案 0 :(得分:0)

Someone on the Alexa forums helped me find my issue.

基本上,我的CustomErrorHandler不能正确访问deviceId并抛出错误。将CustomErrorHandler中的行更改为此后,问题已解决,并且错误处理程序按预期工作。

const deviceId = handlerInput.requestEnvelope.context.System.device.deviceId;

代替

const deviceId = handlerInput.context.System.device.deviceId;

可能还有一个好的做法,就是有一个备份错误处理程序来捕获您的错误处理程序中的错误,该错误处理程序只是打印出错误以避免备份处理程序中出现任何错误。