简体   繁体   中英

Unable to prevent node from crashing and to send an error in a response

Connection.js
 const mysql = require("mysql"); var mysqlConnection = mysql.createConnection({ host: "xxxxx.amazonaws.com", user: "admin", password: "xxx", database: "xxx", multipleStatements: true, }); var connect=()=> return new Promise((resolve,reject)=>{ mysqlConnection.connect((err) => { if (err) { reject ("Failed to connect") } else{ resolve ("Connected") } }); }) module.exports = { mysqlConnection,connect};
server.js
 app.get("/", (req, res) => { var fetchDetail = `xxxx` connect().then((result)=>{ console.log(result) mysqlConnection.query(fetchDetail, (error, result, fields) => { if (error) { console.log(error); } else { console.log("Successfull"); res.send(result); } }); }).catch((err)=>{ res.send(err) }) } );

If I hit the URL when the internet is closed, I want to handle the error that occurs due to connection not established and send this error as a response so I can handle it on the frontend. But what is actually happening is that my node server got crashed with the error and its not sending the err as a response. Am I handling it in the wrong way? What else should I do.

app.get("/", (req, res) => {
  
  var fetchDetail = `xxxx`
   
  connect()
    .then((result)=>{
      console.log(result)
      mysqlConnection.query(fetchDetail, (error, result, fields) => {
        if (error) {
          console.log(error);
        } else {
          console.log("Successfull");
          res.send(result);
        }
      });
    })
    .catch((err)=>{
     let e=new Error("Some thing went wrong")
     e.status=500;
    next(e)

    })
  }
);

app.use(function (err, req, res, next) {
  console.log(err)
  res.status(500).send('Something broke!')
})

I have read the documentation how to handle error in Express from an asynchronous function. https://expressjs.com/en/guide/error-handling.html

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