--- tags: Node.js 直播班 - 2022 春季班 --- # 🏅 Day 22 ## 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> (...略) ``` **uncaughtException 處理範例** ```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)測試) 回報流程 --- 請同學依照下圖教學觀看解答、回報答案:  回報格式:請在「回報區」貼上 CodePen 或 HackMD 連結回報答案 (為了統計人數,請同學依序加上「報數」) <!-- 解答 此題無解答,運行 GitHub 程式碼有正確紀錄錯誤於 server 即可 --> 回報區 --- | 報數 | 組別 / 名字 | codepen / hackMD / 其他回饋 | | ---- | ----------- | ------------------ | |1| 第 5 組 / Hazel | [HackMD@Hazel](https://hackmd.io/@hazelwu/day22) | |2| 第 1 組 / Claire | [GitHub](https://github.com/clairechang0609/metawall-express/blob/main/app.js) || |3| 第 11 組 / Han Lai | [GitHub](https://github.com/x94han/metaWall-backend/blob/main/app.js) | |4| 第 3 組 / Hobby | [Github](https://github.com/hobbyling/metawall-backend/blob/main/app.js) |
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up