--- tags: Node.js 直播班 - 2023 春季班 --- # 🏅 Day 21 - uncaughtException、unhandledRejection 在設計程式時也有可能會有開發者程式沒寫好、沒考慮到的部分,這時可能就因此出現不可預期的錯誤,因此在 Node.js,運行程式出錯時,若是**同步**的程式就會出現 `uncaughtException`,**非同步**程式則會出現 `unhandledRejection` 同步的錯誤例如:app.js 中有出現未宣告過的變數 test 非同步錯誤例如:某 async function 中,未使用到 await,或遠端資料庫連線失敗 (若未使用 catch 接錯誤就會發生 unhandledRejection) 在事件發生時,將錯誤記錄於 server,並在處理後離開此 process **uncaughtException 處理範例** ```javascript // 程式出現重大錯誤時 process.on('uncaughtException', err => { // 記錄錯誤下來,等到服務都處理完後,停掉該 process console.error('Uncaughted Exception!') console.error(err); process.exit(1); }); ``` 出錯時的紀錄會出現: ``` Uncaughted Exception! ReferenceError: test is not defined at Object.<anonymous> (...略) ``` **unhandledRejection 處理範例** ```javascript // 未捕捉到的 catch process.on('unhandledRejection', (reason, promise) => { console.error('未捕捉到的 rejection:', promise, '原因:', reason); // 記錄於 log 上 }); ``` 出錯時的紀錄會出現 ``` 未捕捉到的 rejection: Promise { <rejected> ReferenceError: timeSor is not defined at ...略 } 原因: ReferenceError: timeSor is not defined at ...略 ``` ### 參考資源 - [Event: uncaughtException](https://nodejs.org/api/process.html#event-uncaughtexception) - [Event: unhandledRejection](https://nodejs.org/api/process.html#event-unhandledrejection) ## 題目(將答案寫在 GitHub 並提交至回報區) 將上方兩段處理 uncaughtException、unhandledRejection 錯誤處理加入到自己的專案加入 app.js 中,測試在有錯誤的狀況是否有正確紀錄錯誤,並提交可正確回饋錯誤的 GitHub (也可使用此[專案](https://github.com/dogwantfly/week5-middleware/tree/appError)測試) ## 回報流程 將答案連結貼至底下回報就算完成了喔! 解答位置請參考下圖(需打開程式碼的部分觀看) ![](https://i.imgur.com/vftL5i0.png) <!-- 解答: 此題無解答,運行 GitHub 程式碼有正確紀錄錯誤於 server 即可 --> 回報區 --- | 報數 | 組別/Discord 名字 | Codepen/HackMD/其他回饋 | |:----:|:-----------------------:|:-------------------------------------------------------------------------:| | 1 | 中 4 組 / jimkk159 | [HackMD - Day 21](https://hackmd.io/MR123xg4RHmvf7b0Q6tcFw) | | 1 | 北 10 組 / Benson | [Github - Day 21](https://github.com/ioveasdkre/HexschoolOperation/tree/main/NodejsEnterpriseClass/day40-tasks/day21/app.ts) | | 2 | 北 13 組 / Louisa | [GitHub - Day 21](https://github.com/louisa0416/NodejsEnterpriseClass/tree/master/daily-task/day21) | | 4 | 北 16 組 / 文文 | [GitHub - Day 21](https://github.com/chiawen81/nodeJS_DailyTasks/tree/10e7a1e6ec72947f23075191b751aa983185f6ef) |