您的位置:首页 > Web前端 > Node.js

Node-red catch节点

2015-09-24 00:33 756 查看
catch用于捕获流程中的节点在处理message时抛出的异常,类似于js的try{}catch(){}。

catch节点的js和html文件源码分别如下:

catch.js注册input事件,在捕获的异常时,输出异常msg,如有错误,msg中会包含错误信息error,error下含有message,source.id和source.type等错误具体信息和位置;

[code]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

[code]<script type="text/x-red" data-template-name="catch">
    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
        <input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
    </div>
</script>
<script type="text/x-red" data-help-name="catch">
    <p>Catch errors thrown by nodes on the same tab.</p>
    <p>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.</p>
    <p>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.</p>
    <p>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.</p>
    <p>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 <code>error</code>
       property with the following attributes:
       <ul>
        <li><code>message</code> : the error message</li>
        <li><code>source.id</code> : the id of the node that threw the error</li>
        <li><code>source.type</code> : the type of the node that threw the error</li>
       </ul>
   </p>
   <p>If the message already had a <code>error</code> property, it is copied to <code>_error</code>.</p>
</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格式,流程图如下:



function节点调用throw抛出异常,代码如下:



deploy后,点击inject节点,在debug信息栏可以看到catch捕获到的错误,结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: