简体   繁体   中英

Handle exception in Node.js and send the error output to HTML

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM