--- tags: Node.js 直播班 - 2023 春季班 --- # 🏅 Day 24 - 非同步錯誤管理 在二到四週主線任務中,我們會使用 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/vftL5i0.png) <!-- 解答: // 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" }); } })) ``` --> 回報區 --- | 報數 | 組別/Discord 名字 | Codepen/HackMD/其他回饋 | |:----:|:-----------------------:|:-------------------------------------------------------------------------:| | 1 | 中 4 組 / jimkk159 | [HackMD - Day 24](https://hackmd.io/a7sDy-fsTTyEZYzHXUtkpg) | | 1 | 北 10 組 / Benson | [Github - Day 24](https://github.com/ioveasdkre/HexschoolOperation/tree/main/NodejsEnterpriseClass/day40-tasks/day24/app.ts) | | 2 | 北 13 組 / Louisa | [GitHub - Day 24](https://github.com/louisa0416/NodejsEnterpriseClass/blob/master/daily-task/day24/week5-middleware/routes/posts.js) | | 4 | 北 16 組 / 文文 | [GitHub - Day 24](https://github.com/louisa0416/NodejsEnterpriseClass/blob/master/daily-task/day24/week5-middleware/routes/posts.js) |