我在一個測驗專案中使用“cls-hooked”在 Sequelize 中啟用了 CLS 事務控制,只是為了了解它的要點。因此,它在命令列以及 Express 中都可以正常作業,事務正在自動注入和管理,并且它應該回滾任何錯誤。
下面你可以看到代碼在 Express 中變得多么簡單,我只是將對我的服務層的呼叫包裝在一個單獨的 sequelize 事務函式中。到現在為止還挺好...
router.post('/', (req, res) => {
sequelize.transaction(async () => {
res.status(201).json(await
CountryService().add(req.body));
});
});
router.post('/', async (req, res) => {
sequelize.transaction(async () => {
res.status(201).json(await
CountryService().add(req.body));
});
});
現在問題變成了錯誤處理。我不想為每個端點都“.catch(error => {'do error related stuff here'; })”(更不用說可能從 Express 中“泄漏”的Sequelize 相關錯誤,例如,'拒絕連接。'如果我無法訪問 DBMS)。
我想要一個“包羅萬象的中間件”來處理這一切。
在我的其他專案中,未啟用 CLS 托管事務(因此,我自己提交和回滾,以及將事務實體傳遞給每個 Sequelize 呼叫),我可以將我的錯誤中間件傳遞給 Express 并處理任何意外情況都很好,即使是“express-async-errors”也可以很好地衡量。
現在,無論有沒有“express-async-errors”,有或沒有異步端點(如您在上面看到的,“同步”和“異步”版本),我得到了那些可怕的(節點:2528)UnhandledPromiseRejectionWarning : 錯誤。
具有以下內容:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2528) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我的服務函式和端點都在堆疊跟蹤中,如下所示:
at async Object.add (C:\Users\...\VSCode\sqlize-test\services\country.js:9:16)
at async C:\Users\...\VSCode\sqlize-test\routes\country.js:10:30
所以我們可以說它理解錯誤發生在我的服務層內部,而不是跳轉到我的控制器/休息/api層。
問題是,為什么我的“包羅萬象的中間件”不能捕獲它?它是相同的中間件,我在其他專案中使用的相同配置,沒有使用 CLS 進行嵌套事務,所以我在這里有點迷失。
為了引發錯誤,我通過 POST 向同一個國家/地區發送了兩次,因此它違反了唯一密鑰,但它會發生在 sequelize 驗證錯誤以及任何其他錯誤中。
感謝您的關注。
uj5u.com熱心網友回復:
假設catch all middleware是這樣的:
app.use(function (err, req, res, next) {
logger.error(err)
res.status(500).send(`<pre>${err.stack}</pre>`)
})
您只需要從異步資料庫呼叫中獲取例外:
router.post('/', async (req, res) => {
await sequelize.transaction(async () => {
res.status(201).json(await
CountryService().add(req.body));
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460811.html
標籤:javascript 节点.js 表示 续集.js cls-hooked
上一篇:PHP中的Ajax未定義值
