I have a function which console logs the error in case error exist, I wish to send the same data back to HTML <div>
. The <div>
must only load in case of error and present user with the error msg.
app.js
console.log('Pulling Image from DockerHubn');
const result1 = cp.execSync('docker pull mongo:'+version);
console.log(result1.toString());
Let’s say the above code generates an error and I wish to get the data on my HTML using jQuery AJAX.
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>
Need to handle error exceptions in the above child process (app.js)
and render the data on index.html
ONLY if ERROR exists. If the cp doesn’t return any error, no need to render any data on index.html
Update:
Let’s say in here const result1 = cp.execSync('docker pull mongo:'+version);
I give an incorrect value for version and the child process fails. As per the execSync
syntax I cannot have a callback function to determine the error.
Now the console does display some error msg
Error response from daemon: manifest for mongo:a not found: manifest unknown: manifest unknown
child_process.js:660
throw err;
^
Now if I wish to display the same msg on my HMTL <div>
what do I do?
2
Answers
You can try this –
On your server –
The key is to
catch
the error on the server and return it in the HTTP response. You don’t have to use.json({ ... })
, but it tends to be convenient.error.message
tends to have the type of message you describe, but you can also access other fields like the stack trace, etc. Since the server is returning a statusCode 500, that will trigger theerror
callback, so you will need to add that handler to your request, then add the message to the DOM.