簡體   English   中英

NodeJS Mysql在錯誤時停止服務器崩潰

[英]NodeJS Mysql Stop Server Crash on Error

我正在使用https://github.com/felixge/node-mysql,並且每次mysql查詢拋出錯誤時(例如,如果某行不存在)。 節點服務器崩潰。

connection.connect();

connection.query('SELECT * from table1 where id = 2',  function(err, rows, fields) {
  if (err) console.log(err);
  if (rows[0]) { 
    console.log('The result is  ', rows[0].user);
  }
});
connection.end();

我如何簡單地將錯誤打印到頁面上而不使服務器崩潰。

如果發生錯誤,則代碼為console.log ,但仍然嘗試訪問rows[0] 如果發生錯誤,則rows是不確定的,因此rows[0]將觸發新的錯誤。

else結合長度檢查可輕松固定:

if (err) {
  console.log(err);
} else if (rows.length) { 
  console.log('The result is  ', rows[0].user);
} else {
  console.log("Query didn't return any results.");
}

我更喜歡使用return語句:

connection.connect();

connection.query('SELECT * from table1 where id = 2',  function(err, rows, fields) {
  if (err) return console.log(err);

  if (rows[0]) { 
    console.log('The result is  ', rows[0].user);
  }
});
connection.end();

這是更干凈的IMO,並保證我不會在if語句塊中不應保留的地方保留任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM