在 Java 中,我可以做這樣的事情,我想知道在 NodeJS 中是否可以做這樣的事情?
function is_document_redundant(document) {
// pseudo code, not real
result = mongoose.Model.find(document.id);
if (result != null) {
throw new RedundantDocumentException(document);
}
}
function save_document(document) {
// pseudo code, not real
try {
is_document_redundant(document);
mongoose.Model.save(document);
} catch(err) {
console.log(err)
}
}
需要明確的是,如果此行引發例外:
is_document_redundant(document);
那么這條線不應該發生:
mongoose.Model.save(document);
也就是說,一旦拋出例外,腳本基本上就結束了。
我嘗試撰寫此代碼,但遺憾的是,腳本似乎繼續超出例外。即使代碼是多余的,并且會引發例外:
is_document_redundant(document);
該腳本仍然執行這一行:
mongoose.Model.save(document);
我有多余的檔案堆積在資料庫中。我想知道如何避免這種情況,而不必到處都有一堆丑陋的 catch() 塊。我寧愿讓例外冒泡到頂部并在一個 catch 塊中處理它們,但我需要這些例外來中斷代碼并將控制流直接帶到頂級 catch() 陳述句。
編輯:
好的,現在我正在嘗試使用await但是:
我有一條像這樣開始的 Express 路線:
app.post('/ams', async (req, res) => {
try {
然后嘗試:
let is_redundant = await document_is_redundant(AMS_945, unique_id);
console.log(is_redundant);
if (is_redundant) {
throw new DocumentIsRedundantException(unique_id);
}
但我得到:
SyntaxError: await is only valid in async function
uj5u.com熱心網友回復:
async function is_document_redundant(document) {
// pseudo code, not real
result = await mongoose.Model.find(document.id);
return result != null
}
async function save_document(document) {
// pseudo code, not real
cosnt isRedundant = await is_document_redundant(document)
if (isRedundant) {
mongoose.Model.save(document);
return res.send('success')
} else {
return res.status(404).('refused to save')
}
}
如果你只是想要不同的結果,你不一定需要依賴錯誤。
在客戶端,您可以使用res.ok檢查收到的回應是否不是 200 狀態碼。(客戶端的 try-catch 不起作用,因為手工錯誤不是網路錯誤)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/399733.html
上一篇:OSError:/usr/lib/ghc/ghc-prim-0.5.2.0/libHSghc-prim-0.5.2.0-ghc8.4.4.so:未定義符號:stg_gc_unpt_r1
