Node-red catch节点

catch用于捕获流程中的节点在处理message时抛出的异常,类似于js的try{}catch(){}。
catch节点的js和html文件源码分别如下:
catch.js注册input事件,在捕获的异常时,输出异常msg,如有错误,msg中会包含错误信息error,error下含有message,source.id和source.type等错误具体信息和位置;

module.exports = function(RED) {
    "use strict";//使用js严格模式

    function CatchNode(n) {
        RED.nodes.createNode(this,n);
        var node = this;
        this.on("input",function(msg) {
            this.send(msg); 
        });
    }

    RED.nodes.registerType("catch",CatchNode);
}

catch.html

<script type="text/x-red" data-template-name="catch">
    <div class="form-row">
        
        "text" id="node-input-name" data-i18n="[placeholder]common.label.name">
    div>
script>
<script type="text/x-red" data-help-name="catch">
    

Catch errors thrown by nodes on the same tab.

If a node throws a error whilst handling a message, the flow will typically halt. This node can be used to catch those errors and handle them with a dedicated flow.

The node will catch errors thrown by any node on the same tab. If there are multiple catch nodes on a tab, they will all get triggered.

If an error is thrown within a subflow, the error will get handled by any catch nodes within the subflow. If none exists, the error is propagated up to the tab the subflow instance is on.

The message sent by this node will be the original message if the node that threw the error provided it. The message will have an error property with the following attributes:

  • message : the error message
  • source.id : the id of the node that threw the error
  • source.type : the type of the node that threw the error

If the message already had a error property, it is copied to _error.

script> <script type="text/javascript"> RED.nodes.registerType('catch',{ category: 'input', color:"#e49191", defaults: { name: {value:""} }, inputs:0, outputs:1, icon: "alert.png", label: function() { return this.name||this._("catch.catch"); }, labelStyle: function() { return this.name?"node_label_italic":""; } }); script>

代码中common.label.name,this._(“catch.catch”)均使用了llocales/en-US/messages.json中的值

启动node-red工具测试catch节点,inject节点触发一次异常,function节点抛出异常,debug节点打印出catch捕获msg格式,流程图如下:
Node-red catch节点_第1张图片

function节点调用throw抛出异常,代码如下:
Node-red catch节点_第2张图片

deploy后,点击inject节点,在debug信息栏可以看到catch捕获到的错误,结果如下:
Node-red catch节点_第3张图片

你可能感兴趣的:(node-red)