[英]Exception handling in promise chain
我有一個帶有多個承諾鏈的代碼,如下所示
.then(function(response) {
//my code
})
.then(function(app) {
//my code
})
.then(function() {
//my code
})
如下所示為它們中的每一個添加了異常處理,以便如果一個中斷鏈繼續。
這是處理多個鏈塊異常的正確方法,還是可以遵循任何最佳實踐來處理異常,以便代碼執行失敗時不會中斷。
.then(function(response) {
//my code
})
.catch(e => {})
.then(function(app) {
//my code
})
.catch(e => {})
.then(function() {
//my code
})
.catch(e => {})
如果您的代碼可以適應早期發生的錯誤(無論它是什么),這可能是一種合理的方法,但我總是必須在代碼審查中仔細查看它,因為代碼相當不尋常能夠忽略這樣的錯誤。 代碼大致相當於:
try {
//my code
} catch (e) {
}
try {
//my code
} catch(e) {
}
try {
//my code
} catch(e) {
}
...但改用承諾。 所以這是一個有點懷疑,但也可以是正確的,對於上述同樣的原因是有點懷疑,但可能是正確的,如果你需要同時做的一系列事情,一個,並讓每個人做到即使前一個失敗。
請注意,這意味着后續履行處理app
中的app
將是undefined
:
.then(function(response) {
//my code
})
.catch(e => {})
.then(function(app) { // <=== `app` is `undefined` here
//my code
})
.catch(e => {})
.then(function() {
//my code
})
.catch(e => {})
我只想插入我的 2 美分。
你可以用一個輔助函數來獲得一些樂趣(或者使用更花哨的東西,比如fp-ts
包中的整個Either monad
東西)
const run = async (fn) => {
try {
const result = await fn()
return [result, null]
} catch (err) {
return [null, err]
}
}
並在沒有try\\catch
或.then\\.catch
情況下編寫代碼
const [response, error] = await run(() => fetch('asdfasdf'))
const app = buildApp(response.ok ? await response.json() : { fallback: 'data' })
const [appResponse, appError] = await run(async () => {
await app.compileTemplate()
return app.buildResponse()
})
if (appResponse) {
// ...
}
或者更無用的方法,您可以拋出自定義錯誤,因此您的第一個.catch
塊將能夠執行某些操作。
class AppFromResponseError extends Error {
constructor(message, fallbackApp) {
super(message)
this.name = "ResponseError"
this.app = "fallbackApp"
}
}
builder
.then(function(response) {
if (response.ok !== true)
throw new AppFromResponseError('not ok', minimalApp)
})
.catch(e => {
if (e.app) return e.app
})
.then(app => { /* some kind of app will be here */})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.