--- tags: Node.js 直播班 - 2022 春季班 --- # 🏅 Day 25 ## 非同步錯誤管理 在二到四週主線任務中,我們會使用 try catch 處理 async function 中的錯誤,當 try {...} 中執行的程式發生錯誤就會跑到 catch 目前每個非同步函式中都各有 try catch,可以嘗試將執行非同步函式的錯誤一併接到 function 中處理,以減少每次加上 try catch 的動作 範例 ```javascript // handleErrorAsync.js const handleErrorAsync = function handleErrorAsync(func) { return function (req, res, next) { func(req, res, next).catch( function (error) { return next(error); } ); }; }; module.exports = handleErrorAsync; ``` 將 handleErrorAsync 加入 router 中執行 ```javascript router.get('/', handleErrorAsync(getPosts)) // getPosts 為 async function async(req, res, next) => { ... const post = await Post.find(); res.status(200).json({ status: 'success', results: post.length, data: { post } }); } ``` 運作流程為: - 將非同步函式傳入 `handleErrorAsync()` 並在其中回傳 `function(req, res, next) {...}` 接收 router 的資料`req, res, next` - 再執行傳入的 function,並接上 `catch()`,當傳入的非同步 function 在執行上出錯時,就會統一跑到 `handleErrorAsync()` 的 catch - 在 `catch()` 中會再執行一個 function 並把 error 資料透過 `next()` 交給 app.js 中的[錯誤處理 middleware](https://github.com/gonsakon/express-week4-sample/blob/week5/app.js#L47-L86) 可觀看完整範例 [GitHub](https://github.com/gonsakon/express-week4-sample/tree/week5) 測試 ### 參考資源 [Express 錯誤處理](https://expressjs.com/zh-tw/guide/error-handling.html) ### 題目(將答案寫在 GitHub 並提交至回報區) 嘗試參考上方介紹的方式,在 router 如:POST /posts,加入 `handleErrorAsync()` ,測試當執行 POST 有錯誤時,錯誤可正確透過此 middleware 接到 catch 並由 app.js 中的錯誤處理 middleware 回傳錯誤訊息 測試可正確運作後上傳至 GitHub 提交至回報區 回報流程 --- 請同學依照下圖教學觀看解答、回報答案: ![](https://i.imgur.com/QtL8zEW.png) 回報格式:請在「回報區」貼上 CodePen 或 HackMD 連結回報答案 (為了統計人數,請同學依序加上「報數」) <!-- 解答 // routes/posts.js 範例參考 ```javascript router.post('/', handleErrorAsync( async(req, res, next) => { const data = req.body; if(data.content){ const newPost = await Post.create( { user: data.user, content: data.content, tags: data.tags, type:data.type } ); res.status(200).json({ status: 'success', data: newPost }); }else{ res.status(400).json({ status: 'false', "message": "欄位未填寫正確,或無此 todo ID" }); } })) ``` --> 回報區 --- | 報數 | 組別 / 名字 | codepen / hackMD / 其他回饋 | | ---- | -------------- | -------------------------------------------------- | | 1 | 第 14 組|East | [HackMD](https://hackmd.io/ofyrQEexQAKKdfqm666yQQ) | | 2 | 第 4 組|苡安 | [HackMD](https://hackmd.io/e1HHNhi9Qpy8h_4e281FqA) | |3 |第 9 組 / konstante |[HackMD](https://hackmd.io/mAv804vLSLKWauwKXEcxAw?edit) | |4 |第 5 組 / Hazel |[HackMD@Hazel](https://hackmd.io/@hazelwu/day25) | |5 |第 11 組 / Han Lai |[HackMD](https://hackmd.io/yydTmLSJQ0G35YYo3gpwxQ?view) | |6 |第 4 組 / 小宥 |[HackMD](https://hackmd.io/AEX0xTsxQY2AXKM1z_pqTg) | |7 |第 2 組 / joe |[HackMD](https://hackmd.io/uaRTw9c0TgOrADyXMmGL0Q?view#512-handleErrorAsync) | |8 |第 3 組 / Hobby |[HackMD](https://hackmd.io/@hobbyling/day25) | |9 |第 12 組 / Jimmy |[HackMD](https://hackmd.io/ltH1_SE6R1a9gzjtiULo6A) | |10 |第 16 組 / 皓皓 |[HackMD](https://hackmd.io/@cutecat8110/ry6qnxM_c) | |11 |第 2 組 / wendy | [HackMD](https://hackmd.io/80FIwll1QUa4u0-WoBv-hQ#20220512)|