>我有一个函数,如果存在错误,控制台会记录错误,我希望将相同的数据发送回 HTML<div>
。<div>
必须仅在发生错误时加载,并向用户显示错误消息。
应用.js
console.log('Pulling Image from DockerHubn');
const result1 = cp.execSync('docker pull mongo:'+version);
console.log(result1.toString());
假设上面的代码生成了一个错误,我希望使用 jQuery AJAX 在我的 HTML 上获取数据。
索引.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 存在时才在 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 上显示相同的消息<div>
我该怎么办?
关键是在服务器上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
往往具有您描述的消息类型,但您也可以访问其他字段,如堆栈跟踪等。由于服务器返回的状态代码 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);
}
});
});
你可以试试这个 -
<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)
}