31. Node.js 中的錯誤處理

圖片來源網(wǎng)絡(luò)溯香,侵刪

Errors in Node.js are handled through exceptions.

Creating exceptions

An exception is created using the throw keyword:

throw value

As soon as JavaScript executes this line, the normal program flow is halted and the control is held back to the nearest exception handler.

Usually in client-side code value can be any JavaScript value including a string, a number or an object.

In Node.js, we don't throw strings, we just throw Error objects.

Error objects

An error object is an object that is either an instance of the Error object, or extends the Error class, provided in the Error core module:

throw new Error('Ran out of coffee')

or

class NotEnoughCoffeeError extends Error {
  //...
}
throw new NotEnoughCoffeeError()

Handling exceptions

An exception handler is a try/catch statement.

Any exception raised in the lines of code included in the try block is handled in the corresponding catch block:

try {
  //lines of code
} catch (e) {}

e in this example is the exception value.

You can add multiple handlers, that can catch different kinds of errors.

Catching uncaught exceptions

If an uncaught exception gets thrown during the execution of your program, your program will crash.

To solve this, you listen for the uncaughtException event on the process object:

process.on('uncaughtException', err => {
  console.error('There was an uncaught error', err)
  process.exit(1) //mandatory (as per the Node.js docs)
})

You don't need to import the process core module for this, as it's automatically injected.

Exceptions with promises

Using promises you can chain different operations, and handle errors at the end:

doSomething1()
  .then(doSomething2)
  .then(doSomething3)
  .catch(err => console.error(err))

How do you know where the error occurred? You don't really know, but you can handle errors in each of the functions you call (doSomethingX), and inside the error handler throw a new error, that's going to call the outside catch handler:

const doSomething1 = () => {
  //...
  try {
    //...
  } catch (err) {
    //... handle it locally
    throw new Error(err.message)
  }
  //...
}

To be able to handle errors locally without handling them in the function we call, we can break the chain you can create a function in each then() and process the exception:

doSomething1()
  .then(() => {
    return doSomething2().catch(err => {
      //handle error
      throw err //break the chain!
    })
  })
  .then(() => {
    return doSomething2().catch(err => {
      //handle error
      throw err //break the chain!
    })
  })
  .catch(err => console.error(err))

Error handling with async/await

Using async/await, you still need to catch errors, and you do it this way:

async function someFunction() {
  try {
    await someOtherFunction()
  } catch (err) {
    console.error(err.message)
  }
}

文章來源 node中文官方 http://nodejs.cn/

更多知識點 請關(guān)注:筆墨是小舟

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末词疼,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌赫模,老刑警劉巖袋哼,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件凯沪,死亡現(xiàn)場離奇詭異莱革,居然都是意外死亡,警方通過查閱死者的電腦和手機咽袜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門丸卷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人询刹,你說我怎么就攤上這事谜嫉。” “怎么了凹联?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵骄恶,是天一觀的道長。 經(jīng)常有香客問我匕垫,道長,這世上最難降的妖魔是什么虐呻? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任象泵,我火速辦了婚禮寞秃,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘偶惠。我一直安慰自己春寿,他們只是感情好,可當我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布忽孽。 她就那樣靜靜地躺著绑改,像睡著了一般。 火紅的嫁衣襯著肌膚如雪兄一。 梳的紋絲不亂的頭發(fā)上厘线,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天,我揣著相機與錄音出革,去河邊找鬼造壮。 笑死,一個胖子當著我的面吹牛骂束,可吹牛的內(nèi)容都是我干的耳璧。 我是一名探鬼主播,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼展箱,長吁一口氣:“原來是場噩夢啊……” “哼旨枯!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起混驰,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤攀隔,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后账胧,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體竞慢,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年治泥,在試婚紗的時候發(fā)現(xiàn)自己被綠了筹煮。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡居夹,死狀恐怖败潦,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情准脂,我是刑警寧澤劫扒,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站狸膏,受9級特大地震影響沟饥,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一贤旷、第九天 我趴在偏房一處隱蔽的房頂上張望广料。 院中可真熱鬧,春花似錦幼驶、人聲如沸艾杏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽购桑。三九已至,卻和暖如春氏淑,著一層夾襖步出監(jiān)牢的瞬間勃蜘,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工夸政, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留元旬,地道東北人。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓守问,卻偏偏與公主長得像匀归,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子耗帕,可洞房花燭夜當晚...
    茶點故事閱讀 44,611評論 2 353