You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
window.addEventListener('unhandledrejection',function(event){// the event object has two special properties:alert(event.promise);// [object Promise] - the promise that generated the erroralert(event.reason);// Error: Whoops! - the unhandled error object});
This post is just a different way of looking on async/await error handling. It should not be used as a goto for every async/await function you write and in a lot cases having a single catch at the top will do just fine. Sometimes we don't want to expose the error object of the implementation of the model and want instead to provide a custom error object masking the underlying mongoose error implementation.
window.addEventListener('unhandledrejection',function(event){// the event object has two special properties:alert(event.promise);// [object Promise] - the promise that generated the erroralert(event.reason);// Error: Whoops! - the unhandled error object});
Activity
xxf1996 commentedon Jul 28, 2019
我一般直接在
await
后面的Promise
对象上使用catch
方法;不过更优雅的方式应该是对promise
对象进行一层包装,通过返回值判断是否有异常,如:参考文档:async/await 优雅的错误处理方法 - 掘金
ghost commentedon Jul 28, 2019
@xxf1996 你好,
关于你描述的错误处理方法,我并没有发现它的优雅之处。
考虑以下两份代码,我认为上面的代码更为优雅一些。
xxf1996 commentedon Jul 28, 2019
嗯,确实没啥特别优雅的,都需要套一层;一般情况用
try/catch
就够用了。HCLQ commentedon Jul 28, 2019
玩node时。。他那么写还是比较常见的。。
ghost commentedon Jul 28, 2019
@HCLQ
你是指 callback 中使用的 error-first 的错误处理方式吗?
这种的确是常见,但是返回
Promise<[Error?, any?]>
的async function
我真的没见过。或许可以给些例子?johnsoncheg commentedon Jul 29, 2019
@t532 包装写法可以省去你每次都需要再具体位置使用
try ... catch
或者.catch
jialinhome commentedon Jul 29, 2019
await
加try...catch
async
函数必然返回一个Promose
,所以可以在执行async
函数后加入.catch
unhandledrejection
进行捕获参考:
Async/await
EmiyaYang commentedon Jul 29, 2019
关于两种写法优劣的,可以看看一下这篇外网文章How to write async await without try-catch blocks in Javascript。文章作者可能也是这种写法的创始者,他从go-lang编程中获得灵感,使用ts造了相应的轮子:await-to-js。
ghost commentedon Jul 30, 2019
@EmiyaYang
Golang 的错误处理方式好处是可以不用被强迫在错误发生时即进行处理,然而却无法在同一个地方 handle 多个错误(除了
ErrorGroup
这种丑陋的方式)。所以两种方式都各有优劣,还是看需求用吧。这篇博客的作者也写了:EragonBubble commentedon Aug 1, 2019
try-catch
Kntt commentedon Aug 10, 2019
我使用装饰器来处理, 避免重复写trycatch
assmdx commentedon Dec 11, 2019
@xxf1996 写的挺好的,每次写代码的时候总感觉大括号的嵌套层数和代码的不稳定性成正比。。
smile-2008 commentedon Sep 30, 2021
xiaoqiangz commentedon Jun 28, 2022
try {
const data = await asyncFn()
/* do sth w/ data /
} catch (err) {
/ handle err */
}