1

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 DockerHub\n');
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 2

1

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.

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 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 the error callback, so you will need to add that handler to your request, then add the message to the 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);
    }
  });    
});
Sign up to request clarification or add additional context in comments.

3 Comments

Could you do me me another favour? I have a table <table id="tab1"></table> I'd like to hide it in case an error occurs and the error function executes. Tried including $("#table1").hide(); inside error function but it doesn't seem to work this way.
Hm, I would expect .hide() to work. I notice your id is tab1, but you typed #table1 in the comment, perhaps that's the source of the problem?
A typo error id is in fact table1 in both cases, although I have AJAX complete function where I have declared $("#table1").show(); is that why I still see the table even if error exists?
1

You can try this -

<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>

On your server -

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)
 }

8 Comments

Also, consider using the new fetch API available in vanilla JS, instead of $.ajax
Additionally, you can display the err inside the div , use $("#errorReport").text(Error occured! ' + err');, a line before $("#errorReport").show();
So by adding error function to my ajax call does help to some extent. However, I wish to display the console error message inside my html <div> now it simple displays Error msg with [object][object].
I have added few more details in my question. Also, execSync() is inside a callback function so most likely the error retuned from my Node.js API is not even for for execSync.
Have you tried wrapping the execSync in try catch block ? See the updated answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.