AWS API Gateway Websocket UnknownError

时间:2019-04-15 11:54:03

标签: amazon-web-services websocket aws-api-gateway

作为承诺,进行SDK postToConnection()调用时我们遇到错误,下面提供了完整的错误详细信息。同一功能中具有不同连接ID的其他调用成功进行。预期的410个连接错误在几毫秒内正确发生,并得到了妥善处理。

然后,此错误需要40秒钟到一分钟多的时间才能返回,这导致它总是在Web socket API中导致“端点请求超时”错误,因为它具有30秒的最大请求超时。是否有人曾经历过此问题和/或实施了任何解决方案?感谢您提出任何解决此问题的想法。

  

UnknownError:与Object.extractError(/opt/nodejs/node_modules/aws-sdk/lib/protocol/json.js:51:27)的端点通信时出现网络错误

3 个答案:

答案 0 :(得分:2)

为避免在无服务器上使用websocket时遇到410的麻烦,请不要忘记捕获异常:

export const ApiGatewayConnector = (event) => {

  const endpoint = process.env.IS_OFFLINE
            ? 'http://localhost:3001'
            : `${event.requestContext.domainName}/${event.requestContext.stage}`
            const apiVersion = '2018-11-29'
            return new AWS.ApiGatewayManagementApi({ apiVersion, endpoint })
}

....

if (event.requestContext.stage == 'local') {
              await ApiGatewayConnector(event)
              .postToConnection({ ConnectionId, Data })
              .promise()
              .catch(_ => removeId(ConnectionId));<----- N.B. Remove disconnected IDs
            } else {
              await ws.send(Data, ConnectionId)
            }
}
        

答案 1 :(得分:1)

您是否要在连接处理程序中使用postToConnection?仅在连接处理程序返回statusCode 200后在 中创建websocket连接。您不应在连接处理程序内部使用postToConnection。

答案 2 :(得分:0)

在响应$ connect事件时调用.postToConnection时抛出该错误。 您可以正确调用.postConnection来回答$ default事件。​​

// index.js
// the handler is defined as: index.handler

const AWS = require("aws-sdk");

exports.handler = function (event, context, callback) {

    console.log('event.requestContext.eventType', event && event.requestContext && event.requestContext.eventType)

    if (event.requestContext.eventType === "CONNECT") {

        console.log('$connect event')

        // calling apigwManagementApi.postToConnection will throw an exception

        callback(null, {
            statusCode: 200,
            body: "Connected"
        });

    } else if (event.requestContext.eventType === "DISCONNECT") {

        console.log('$disconnect event')

        // calling apigwManagementApi.postToConnection is pointless since the client has disconneted

        callback(null, {
            statusCode: 200,
            body: "Disconnected"
        });
    } else {

        console.log('$default event')

        const ConnectionId = event.requestContext.connectionId
        const bodyString = event.body
        const Data = bodyString

        const apigwManagementApi = new AWS.ApiGatewayManagementApi({
            apiVersion: "2018-11-29",
            endpoint: event.requestContext.domainName + "/" + event.requestContext.stage
        });

        apigwManagementApi
        .postToConnection({ ConnectionId, Data })
        .promise().then(() => {

            callback(null, {
                statusCode: 200,
                body: "Disconnected"
            });

        })

    }

};