【问题标题】:Handle exception in Node.js and send the error output to HTML在 Node.js 中处理异常并将错误输出发送到 HTML
【发布时间】:2020-05-24 06:31:45
【问题描述】:

我有一个功能,如果存在错误,控制台会记录错误,我希望将相同的数据发送回 HTML <div><div> 只能在出现错误的情况下加载,并向用户显示错误消息。

app.js

console.log('Pulling Image from DockerHub\n');
const result1 = cp.execSync('docker pull mongo:'+version);
console.log(result1.toString());

假设上面的代码产生了一个错误,我希望使用 jQuery AJAX 在我的 HTML 中获取数据。

index.html

<div id="errorReport"></div>

<script type="text/javascript">
        $(document).ready(function(){     
            $.ajax({
                    url: "http://localhost:8090/api/route1",
                    type: 'POST',
                    dataType:'json', 
                    success: function(res) {
                        console.log(res);
                    }
                });    
            });                   
</script>

需要在上述子进程(app.js) 中处理错误异常,并仅在存在ERROR 时才在index.html 上渲染数据。如果cp没有返回任何错误,则无需在index.html上渲染任何数据

更新: 假设在这里const result1 = cp.execSync('docker pull mongo:'+version); 我为版本提供了不正确的值,并且子进程失败。根据execSync 语法,我无法使用回调函数来确定错误。

现在控制台确实显示了一些错误消息

Error response from daemon: manifest for mongo:a not found: manifest unknown: manifest unknown
child_process.js:660
    throw err;
    ^

现在,如果我想在我的 HMTL &lt;div&gt; 上显示相同的消息,我该怎么办?

【问题讨论】:

    标签: javascript jquery node.js ajax express


    【解决方案1】:

    关键是catch服务器上的错误并在HTTP响应中返回。您不必使用.json({ ... }),但它往往很方便。

    try {
      cp.execSync(`docker pull mongo:'+version`);
      res.status(200)
    } catch (error) {
      // catch the error and return it's message to the client
      res.status(500).json({ error: error.message })
    }
    

    error.message 往往具有您描述的消息类型,但您也可以访问堆栈跟踪等其他字段。由于服务器返回 statusCode 500,这将触发 error 回调,所以您需要将该处理程序添加到您的请求中,然后将消息添加到 DOM。

    $.ajax({
        url: "http://localhost:8090/api/route1",
        type: 'POST',
        dataType:'json', 
        success: function(res) {
            console.log(res);
        },
        error: function(xhr, textStatus, errorThrown) {
          // parse the JSON from the server
          const json = JSON.parse(xhr.responseText);
          // finally, set the div's text to the error
          $("#errorReport").text(json.error);
        }
      });    
    });
    

    【讨论】:

    • 你能帮我一个忙吗?我有一个表&lt;table id="tab1"&gt;&lt;/table&gt; 我想隐藏它以防发生错误并执行错误函数。尝试在错误函数中包含$("#table1").hide();,但它似乎无法以这种方式工作。
    • 嗯,我希望.hide() 能够工作。我注意到你的 id 是 tab1,但你在评论中输入了 #table1,也许这就是问题的根源?
    • 在这两种情况下,错字错误 id 实际上都是 table1,虽然我有 AJAX 完整功能,我已经声明了 $("#table1").show();,这就是为什么即使存在错误我仍然可以看到表格?
    【解决方案2】:

    你可以试试这个——

    <div id="errorReport"></div>
    
    <script type="text/javascript">
            $(document).ready(function(){    
                $("#errorReport").hide();
                $.ajax({
                        url: "http://localhost:8090/api/route1",
                        type: 'POST',
                        dataType:'json', 
                        success: function(res, status) {
                            if(status === 500){
                               $("#errorReport").show();
                            }
                            console.log(res);
                        }
                    });    
                });                   
    </script>
    

    在您的服务器上 -

    try {
      cp.execSync(`docker pull mongo:'+version`);
      res.status(200)
     } catch (error) {
      //catch the error here and handle it accordingly by sending error response to client
     res.status(500)
     }
    

    【讨论】:

    • 另外,考虑使用 vanilla JS 中可用的新 fetch API,而不是 $.ajax
    • 另外,您可以在div 内显示错误,使用$("#errorReport").text(Error occured! ' + err');$("#errorReport").show(); 之前的一行
    • 因此,通过在我的 ajax 调用中添加错误函数确实在一定程度上有所帮助。但是,我希望在我的 html &lt;div&gt; 中显示控制台错误消息,现在它可以简单地显示带有 [object][object] 的错误消息。
    • 我在我的问题中添加了更多细节。此外,execSync() 在回调函数中,因此很可能从我的 Node.js API 重新调整的错误甚至不适用于execSync
    • 您是否尝试将execSync 包装在try catch 块中?查看更新的答案。
    猜你喜欢
    • 2022-09-28
    • 1970-01-01
    • 2016-12-31
    • 2015-08-06
    • 1970-01-01
    • 2011-09-12
    • 2011-04-07
    • 1970-01-01
    • 2013-06-28
    相关资源
    最近更新 更多