node.js - 如何解决:在 Node.js 服务器的 onclosenexttick 处过早关闭?
问题描述
如何解决此错误,我正在使用 AWS IoT 运行我的 Node.js,然后它有时会显示此错误:
throw er; // Unhandled 'error' event
^
Error: How (/home/ec2-user/work/nodejs_27_01/node_modules/end-of-stream/index.js:54: 86)
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Emitted 'error' event on DeviceClient instance at:
at MqttClient.<anonymous> (/home/ec2-user/work/nodejs_27_01/node_modules/aws-iot-device-sdk/ device/index.js:772:15)
at MqttClient.emit (events.js:333:22)
at MqttClient.EventEmitter.emit (domain.js:485:12)
at TLSSocket.f (/home/ec2-user/work/nodejs_27_01/node_modules/once/once.js:25:25)
at onclosenexttick (/home/ec2-user/work/nodejs_27_01/node_modules/end-of-stream/index.js:54: 73)
解决方案
这可能有多种原因:
具有相同 ClientId 的多个连接
clientId 一次只能用于一个连接。如果在建立另一个连接时使用相同的 clientId 进行连接,则旧连接将被丢弃(这会导致过早关闭错误)并建立新连接。
客户端正在使用已在使用的客户端 ID。在这种情况下,已经连接的客户端将被断开 [...]。(来源)
权限
如果设备(来自aws-iot-device-sdk-js 的 mqtt.Client)没有正确的权限来连接和/或发布/订阅/接收给定主题的消息,则可能会发生此错误。
有关更多文档,请参见此处:https ://docs.aws.amazon.com/iot/latest/developerguide/pub-sub-policy.html
该策略应如下所示(示例显示Cloudformation 物联网策略资源):
MyIotThingsPolicy:
Type: AWS::IoT::Policy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Action: iot:Connect
Effect: Allow
Resource: !Join [ "", [!Sub "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:client/",
"${iot:ClientId}"] ]
- Action: iot:Receive
Effect: Allow
Resource: !Join [ "", [!Sub "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/",
"${iot:ClientId}/eg/your/broadcast/topic"] ]
- Action: iot:Subscribe
Effect: Allow
Resource: !Join [ "", [!Sub "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topicfilter/",
"${iot:ClientId}/eg/your/broadcast/topic"] ]
- Action: iot:Publish
Effect: Allow
Resource: !Join [ "", [!Sub "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/",
"${iot:ClientId}/eg/your/publish/topic"] ]
这!Join
是必要的,因为 Cloudformation 会尝试解析${iot:ClientId}
,这是一个运行时值,在部署期间是未知的。
故障排除
正如Sandeep Patel还建议的那样,如果你想在客户端对这种情况采取行动,你应该实现一个错误回调:
device.on('error', (error) => { // error.message might be 'premature close' });
You can also look for
disconnectReason
on the topic$aws/events/presence/disconnected/<clientId>
, see: https://docs.aws.amazon.com/iot/latest/developerguide/life-cycle-events.html